<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlxs - XS language reference manual - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlxs">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlxs.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlxs">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlxs">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlxs">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlxs">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlxs">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlxs">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlxs">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlxs">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlxs">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlxs">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlxs">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlxs">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlxs">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlxs">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlxs">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlxs">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlxs">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlxs">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlxs">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlxs">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlxs">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlxs">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlxs">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlxs">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlxs">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlxs">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlxs">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlxs">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlxs">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlxs">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlxs">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlxs">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlxs">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlxs">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlxs">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlxs">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlxs">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlxs">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlxs">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlxs">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlxs">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlxs">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlxs">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlxs">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlxs">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlxs">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlxs">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlxs">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlxs">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlxs">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlxs">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlxs">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlxs">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlxs">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlxs">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlxs">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlxs">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlxs">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlxs">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlxs">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlxs">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlxs">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlxs">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlxs">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlxs">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlxs">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlxs">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlxs">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlxs">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlxs">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlxs">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlxs">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlxs">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlxs">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlxs">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlxs">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlxs">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlxs">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlxs">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlxs">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlxs.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlxs">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlxs">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlxs">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlxs">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlxs">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlxs">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlxs">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlxs">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlxs">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlxs">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlxs">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlxs">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlxs">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlxs">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlxs">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlxs">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlxs">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlxs">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlxs">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlxs">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlxs">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlxs">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlxs">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlxs">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlxs">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlxs">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlxs">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlxs">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlxs">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlxs">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlxs">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlxs">5.35.1</a>
          <a class="dropdown-item active" href="perlxs.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlxs.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlxs.html">perlxs</a>
          <div id="more">
            (<a href="perlxs.txt">source</a>,
            <a href="https://metacpan.org/pod/perlxs">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlxs.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Introduction">Introduction</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#On-The-Road">On The Road</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-Anatomy-of-an-XSUB">The Anatomy of an XSUB</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-Argument-Stack">The Argument Stack</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-RETVAL-Variable">The RETVAL Variable</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Returning-SVs,-AVs-and-HVs-through-RETVAL">Returning SVs, AVs and HVs through RETVAL</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-MODULE-Keyword">The MODULE Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-PACKAGE-Keyword">The PACKAGE Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-PREFIX-Keyword">The PREFIX Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-OUTPUT:-Keyword">The OUTPUT: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-NO_OUTPUT-Keyword">The NO_OUTPUT Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-CODE:-Keyword">The CODE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-INIT:-Keyword">The INIT: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-NO_INIT-Keyword">The NO_INIT Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-TYPEMAP:-Keyword">The TYPEMAP: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Initializing-Function-Parameters">Initializing Function Parameters</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Default-Parameter-Values">Default Parameter Values</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-PREINIT:-Keyword">The PREINIT: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-SCOPE:-Keyword">The SCOPE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-INPUT:-Keyword">The INPUT: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT-Keywords">The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT Keywords</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-length(NAME)-Keyword">The length(NAME) Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Variable-length-Parameter-Lists">Variable-length Parameter Lists</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-C_ARGS:-Keyword">The C_ARGS: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-PPCODE:-Keyword">The PPCODE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Returning-Undef-And-Empty-Lists">Returning Undef And Empty Lists</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-REQUIRE:-Keyword">The REQUIRE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-CLEANUP:-Keyword">The CLEANUP: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-POSTCALL:-Keyword">The POSTCALL: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-BOOT:-Keyword">The BOOT: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-VERSIONCHECK:-Keyword">The VERSIONCHECK: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-PROTOTYPES:-Keyword">The PROTOTYPES: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-PROTOTYPE:-Keyword">The PROTOTYPE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-ALIAS:-Keyword">The ALIAS: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-OVERLOAD:-Keyword">The OVERLOAD: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-FALLBACK:-Keyword">The FALLBACK: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-INTERFACE:-Keyword">The INTERFACE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-INTERFACE_MACRO:-Keyword">The INTERFACE_MACRO: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-INCLUDE:-Keyword">The INCLUDE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-INCLUDE_COMMAND:-Keyword">The INCLUDE_COMMAND: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-CASE:-Keyword">The CASE: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-EXPORT_XSUB_SYMBOLS:-Keyword">The EXPORT_XSUB_SYMBOLS: Keyword</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#The-&amp;-Unary-Operator">The &amp; Unary Operator</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Inserting-POD,-Comments-and-C-Preprocessor-Directives">Inserting POD, Comments and C Preprocessor Directives</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Using-XS-With-C++">Using XS With C++</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Interface-Strategy">Interface Strategy</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Perl-Objects-And-C-Structures">Perl Objects And C Structures</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Safely-Storing-Static-Data-in-XS">Safely Storing Static Data in XS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlxs.html#MY_CXT-REFERENCE">MY_CXT REFERENCE</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#Thread-aware-system-interfaces">Thread-aware system interfaces</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#EXAMPLES">EXAMPLES</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#CAVEATS">CAVEATS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#XS-VERSION">XS VERSION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlxs.html#AUTHOR">AUTHOR</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlxs.html#NAME">#</a>NAME</h1>

<p>perlxs - XS language reference manual</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlxs.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<h2 id="Introduction"><a class="permalink" href="perlxs.html#Introduction">#</a>Introduction</h2>

<p>XS is an interface description file format used to create an extension interface between Perl and C code (or a C library) which one wishes to use with Perl. The XS interface is combined with the library to create a new library which can then be either dynamically loaded or statically linked into perl. The XS interface description is written in the XS language and is the core component of the Perl extension interface.</p>

<p>Before writing XS, read the <a href="perlxs.html#CAVEATS">&quot;CAVEATS&quot;</a> section below.</p>

<p>An <b>XSUB</b> forms the basic unit of the XS interface. After compilation by the <b>xsubpp</b> compiler, each XSUB amounts to a C function definition which will provide the glue between Perl calling conventions and C calling conventions.</p>

<p>The glue code pulls the arguments from the Perl stack, converts these Perl values to the formats expected by a C function, call this C function, transfers the return values of the C function back to Perl. Return values here may be a conventional C return value or any C function arguments that may serve as output parameters. These return values may be passed back to Perl either by putting them on the Perl stack, or by modifying the arguments supplied from the Perl side.</p>

<p>The above is a somewhat simplified view of what really happens. Since Perl allows more flexible calling conventions than C, XSUBs may do much more in practice, such as checking input parameters for validity, throwing exceptions (or returning undef/empty list) if the return value from the C function indicates failure, calling different C functions based on numbers and types of the arguments, providing an object-oriented interface, etc.</p>

<p>Of course, one could write such glue code directly in C. However, this would be a tedious task, especially if one needs to write glue for multiple C functions, and/or one is not familiar enough with the Perl stack discipline and other such arcana. XS comes to the rescue here: instead of writing this glue C code in long-hand, one can write a more concise short-hand <i>description</i> of what should be done by the glue, and let the XS compiler <b>xsubpp</b> handle the rest.</p>

<p>The XS language allows one to describe the mapping between how the C routine is used, and how the corresponding Perl routine is used. It also allows creation of Perl routines which are directly translated to C code and which are not related to a pre-existing C function. In cases when the C interface coincides with the Perl interface, the XSUB declaration is almost identical to a declaration of a C function (in K&amp;R style). In such circumstances, there is another tool called <code>h2xs</code> that is able to translate an entire C header file into a corresponding XS file that will provide glue to the functions/macros described in the header file.</p>

<p>The XS compiler is called <b>xsubpp</b>. This compiler creates the constructs necessary to let an XSUB manipulate Perl values, and creates the glue necessary to let Perl call the XSUB. The compiler uses <b>typemaps</b> to determine how to map C function parameters and output values to Perl values and back. The default typemap (which comes with Perl) handles many common C types. A supplementary typemap may also be needed to handle any special structures and types for the library being linked. For more information on typemaps, see <a href="perlxstypemap.html">perlxstypemap</a>.</p>

<p>A file in XS format starts with a C language section which goes until the first <code>MODULE =</code> directive. Other XS directives and XSUB definitions may follow this line. The &quot;language&quot; used in this part of the file is usually referred to as the XS language. <b>xsubpp</b> recognizes and skips POD (see <a href="perlpod.html">perlpod</a>) in both the C and XS language sections, which allows the XS file to contain embedded documentation.</p>

<p>See <a href="perlxstut.html">perlxstut</a> for a tutorial on the whole extension creation process.</p>

<p>Note: For some extensions, Dave Beazley&#39;s SWIG system may provide a significantly more convenient mechanism for creating the extension glue code. See <a href="http://www.swig.org/">http://www.swig.org/</a> for more information.</p>

<p>For simple bindings to C libraries as well as other machine code libraries, consider instead using the much simpler <a href="http://sourceware.org/libffi/">libffi</a> interface via CPAN modules like <a href="./FFI::Platypus.html">FFI::Platypus</a> or <a href="./FFI::Raw.html">FFI::Raw</a>.</p>

<h2 id="On-The-Road"><a class="permalink" href="perlxs.html#On-The-Road">#</a><a id="On"></a>On The Road</h2>

<p>Many of the examples which follow will concentrate on creating an interface between Perl and the ONC+ RPC bind library functions. The rpcb_gettime() function is used to demonstrate many features of the XS language. This function has two parameters; the first is an input parameter and the second is an output parameter. The function also returns a status value.</p>

<pre><code>bool_t rpcb_gettime(const char *host, time_t *timep);</code></pre>

<p>From C this function will be called with the following statements.</p>

<pre><code>#include &lt;rpc/rpc.h&gt;
bool_t status;
time_t timep;
status = rpcb_gettime( &quot;localhost&quot;, &amp;timep );</code></pre>

<p>If an XSUB is created to offer a direct translation between this function and Perl, then this XSUB will be used from Perl with the following code. The $status and $timep variables will contain the output of the function.</p>

<pre><code>use RPC;
$status = rpcb_gettime( &quot;localhost&quot;, $timep );</code></pre>

<p>The following XS file shows an XS subroutine, or XSUB, which demonstrates one possible interface to the rpcb_gettime() function. This XSUB represents a direct translation between C and Perl and so preserves the interface even from Perl. This XSUB will be invoked from Perl with the usage shown above. Note that the first three #include statements, for <code>EXTERN.h</code>, <code>perl.h</code>, and <code>XSUB.h</code>, will always be present at the beginning of an XS file. This approach and others will be expanded later in this document. A #define for <code>PERL_NO_GET_CONTEXT</code> should be present to fetch the interpreter context more efficiently, see <a href="perlguts.html#How-multiple-interpreters-and-concurrency-are-supported">perlguts</a> for details.</p>

<pre><code class="plaintext">#define PERL_NO_GET_CONTEXT
#include &quot;EXTERN.h&quot;
#include &quot;perl.h&quot;
#include &quot;XSUB.h&quot;
#include &lt;rpc/rpc.h&gt;

MODULE = RPC  PACKAGE = RPC

bool_t
rpcb_gettime(host,timep)
     char *host
     time_t &amp;timep
   OUTPUT:
     timep</code></pre>

<p>Any extension to Perl, including those containing XSUBs, should have a Perl module to serve as the bootstrap which pulls the extension into Perl. This module will export the extension&#39;s functions and variables to the Perl program and will cause the extension&#39;s XSUBs to be linked into Perl. The following module will be used for most of the examples in this document and should be used from Perl with the <code>use</code> command as shown earlier. Perl modules are explained in more detail later in this document.</p>

<pre><code>package RPC;

require Exporter;
require DynaLoader;
@ISA = qw(Exporter DynaLoader);
@EXPORT = qw( rpcb_gettime );

bootstrap RPC;
1;</code></pre>

<p>Throughout this document a variety of interfaces to the rpcb_gettime() XSUB will be explored. The XSUBs will take their parameters in different orders or will take different numbers of parameters. In each case the XSUB is an abstraction between Perl and the real C rpcb_gettime() function, and the XSUB must always ensure that the real rpcb_gettime() function is called with the correct parameters. This abstraction will allow the programmer to create a more Perl-like interface to the C function.</p>

<h2 id="The-Anatomy-of-an-XSUB"><a class="permalink" href="perlxs.html#The-Anatomy-of-an-XSUB">#</a><a id="The"></a>The Anatomy of an XSUB</h2>

<p>The simplest XSUBs consist of 3 parts: a description of the return value, the name of the XSUB routine and the names of its arguments, and a description of types or formats of the arguments.</p>

<p>The following XSUB allows a Perl program to access a C library function called sin(). The XSUB will imitate the C function which takes a single argument and returns a single value.</p>

<pre><code class="plaintext">double
sin(x)
  double x</code></pre>

<p>Optionally, one can merge the description of types and the list of argument names, rewriting this as</p>

<pre><code class="plaintext">double
sin(double x)</code></pre>

<p>This makes this XSUB look similar to an ANSI C declaration. An optional semicolon is allowed after the argument list, as in</p>

<pre><code>double
sin(double x);</code></pre>

<p>Parameters with C pointer types can have different semantic: C functions with similar declarations</p>

<pre><code>bool string_looks_as_a_number(char *s);
bool make_char_uppercase(char *c);</code></pre>

<p>are used in absolutely incompatible manner. Parameters to these functions could be described <b>xsubpp</b> like this:</p>

<pre><code class="plaintext">char *  s
char    &amp;c</code></pre>

<p>Both these XS declarations correspond to the <code>char*</code> C type, but they have different semantics, see <a href="perlxs.html#The-%26-Unary-Operator">&quot;The &amp; Unary Operator&quot;</a>.</p>

<p>It is convenient to think that the indirection operator <code>*</code> should be considered as a part of the type and the address operator <code>&amp;</code> should be considered part of the variable. See <a href="perlxstypemap.html">perlxstypemap</a> for more info about handling qualifiers and unary operators in C types.</p>

<p>The function name and the return type must be placed on separate lines and should be flush left-adjusted.</p>

<pre><code class="plaintext">  INCORRECT                        CORRECT

  double sin(x)                    double
    double x                       sin(x)
				     double x</code></pre>

<p>The rest of the function description may be indented or left-adjusted. The following example shows a function with its body left-adjusted. Most examples in this document will indent the body for better readability.</p>

<pre><code class="plaintext">CORRECT

double
sin(x)
double x</code></pre>

<p>More complicated XSUBs may contain many other sections. Each section of an XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:. However, the first two lines of an XSUB always contain the same data: descriptions of the return type and the names of the function and its parameters. Whatever immediately follows these is considered to be an INPUT: section unless explicitly marked with another keyword. (See <a href="perlxs.html#The-INPUT%3A-Keyword">&quot;The INPUT: Keyword&quot;</a>.)</p>

<p>An XSUB section continues until another section-start keyword is found.</p>

<h2 id="The-Argument-Stack"><a class="permalink" href="perlxs.html#The-Argument-Stack">#</a><a id="The1"></a>The Argument Stack</h2>

<p>The Perl argument stack is used to store the values which are sent as parameters to the XSUB and to store the XSUB&#39;s return value(s). In reality all Perl functions (including non-XSUB ones) keep their values on this stack all the same time, each limited to its own range of positions on the stack. In this document the first position on that stack which belongs to the active function will be referred to as position 0 for that function.</p>

<p>XSUBs refer to their stack arguments with the macro <b>ST(x)</b>, where <i>x</i> refers to a position in this XSUB&#39;s part of the stack. Position 0 for that function would be known to the XSUB as ST(0). The XSUB&#39;s incoming parameters and outgoing return values always begin at ST(0). For many simple cases the <b>xsubpp</b> compiler will generate the code necessary to handle the argument stack by embedding code fragments found in the typemaps. In more complex cases the programmer must supply the code.</p>

<h2 id="The-RETVAL-Variable"><a class="permalink" href="perlxs.html#The-RETVAL-Variable">#</a><a id="The2"></a>The RETVAL Variable</h2>

<p>The RETVAL variable is a special C variable that is declared automatically for you. The C type of RETVAL matches the return type of the C library function. The <b>xsubpp</b> compiler will declare this variable in each XSUB with non-<code>void</code> return type. By default the generated C function will use RETVAL to hold the return value of the C library function being called. In simple cases the value of RETVAL will be placed in ST(0) of the argument stack where it can be received by Perl as the return value of the XSUB.</p>

<p>If the XSUB has a return type of <code>void</code> then the compiler will not declare a RETVAL variable for that function. When using a PPCODE: section no manipulation of the RETVAL variable is required, the section may use direct stack manipulation to place output values on the stack.</p>

<p>If PPCODE: directive is not used, <code>void</code> return value should be used only for subroutines which do not return a value, <i>even if</i> CODE: directive is used which sets ST(0) explicitly.</p>

<p>Older versions of this document recommended to use <code>void</code> return value in such cases. It was discovered that this could lead to segfaults in cases when XSUB was <i>truly</i> <code>void</code>. This practice is now deprecated, and may be not supported at some future version. Use the return value <code>SV *</code> in such cases. (Currently <code>xsubpp</code> contains some heuristic code which tries to disambiguate between &quot;truly-void&quot; and &quot;old-practice-declared-as-void&quot; functions. Hence your code is at mercy of this heuristics unless you use <code>SV *</code> as return value.)</p>

<h2 id="Returning-SVs,-AVs-and-HVs-through-RETVAL"><a class="permalink" href="perlxs.html#Returning-SVs,-AVs-and-HVs-through-RETVAL">#</a><a id="Returning"></a><a id="Returning-SVs-AVs-and-HVs-through-RETVAL"></a>Returning SVs, AVs and HVs through RETVAL</h2>

<p>When you&#39;re using RETVAL to return an <code>SV *</code>, there&#39;s some magic going on behind the scenes that should be mentioned. When you&#39;re manipulating the argument stack using the ST(x) macro, for example, you usually have to pay special attention to reference counts. (For more about reference counts, see <a href="perlguts.html">perlguts</a>.) To make your life easier, the typemap file automatically makes <code>RETVAL</code> mortal when you&#39;re returning an <code>SV *</code>. Thus, the following two XSUBs are more or less equivalent:</p>

<pre><code>void
alpha()
    PPCODE:
        ST(0) = newSVpv(&quot;Hello World&quot;,0);
        sv_2mortal(ST(0));
        XSRETURN(1);

SV *
beta()
    CODE:
        RETVAL = newSVpv(&quot;Hello World&quot;,0);
    OUTPUT:
        RETVAL</code></pre>

<p>This is quite useful as it usually improves readability. While this works fine for an <code>SV *</code>, it&#39;s unfortunately not as easy to have <code>AV *</code> or <code>HV *</code> as a return value. You <i>should</i> be able to write:</p>

<pre><code>AV *
array()
    CODE:
        RETVAL = newAV();
        /* do something with RETVAL */
    OUTPUT:
        RETVAL</code></pre>

<p>But due to an unfixable bug (fixing it would break lots of existing CPAN modules) in the typemap file, the reference count of the <code>AV *</code> is not properly decremented. Thus, the above XSUB would leak memory whenever it is being called. The same problem exists for <code>HV *</code>, <code>CV *</code>, and <code>SVREF</code> (which indicates a scalar reference, not a general <code>SV *</code>). In XS code on perls starting with perl 5.16, you can override the typemaps for any of these types with a version that has proper handling of refcounts. In your <code>TYPEMAP</code> section, do</p>

<pre><code class="plaintext">AV*	T_AVREF_REFCOUNT_FIXED</code></pre>

<p>to get the repaired variant. For backward compatibility with older versions of perl, you can instead decrement the reference count manually when you&#39;re returning one of the aforementioned types using <code>sv_2mortal</code>:</p>

<pre><code>AV *
array()
    CODE:
        RETVAL = newAV();
        sv_2mortal((SV*)RETVAL);
        /* do something with RETVAL */
    OUTPUT:
        RETVAL</code></pre>

<p>Remember that you don&#39;t have to do this for an <code>SV *</code>. The reference documentation for all core typemaps can be found in <a href="perlxstypemap.html">perlxstypemap</a>.</p>

<h2 id="The-MODULE-Keyword"><a class="permalink" href="perlxs.html#The-MODULE-Keyword">#</a><a id="The3"></a>The MODULE Keyword</h2>

<p>The MODULE keyword is used to start the XS code and to specify the package of the functions which are being defined. All text preceding the first MODULE keyword is considered C code and is passed through to the output with POD stripped, but otherwise untouched. Every XS module will have a bootstrap function which is used to hook the XSUBs into Perl. The package name of this bootstrap function will match the value of the last MODULE statement in the XS source files. The value of MODULE should always remain constant within the same XS file, though this is not required.</p>

<p>The following example will start the XS code and will place all functions in a package named RPC.</p>

<pre><code class="plaintext">MODULE = RPC</code></pre>

<h2 id="The-PACKAGE-Keyword"><a class="permalink" href="perlxs.html#The-PACKAGE-Keyword">#</a><a id="The4"></a>The PACKAGE Keyword</h2>

<p>When functions within an XS source file must be separated into packages the PACKAGE keyword should be used. This keyword is used with the MODULE keyword and must follow immediately after it when used.</p>

<pre><code class="plaintext">MODULE = RPC  PACKAGE = RPC

[ XS code in package RPC ]

MODULE = RPC  PACKAGE = RPCB

[ XS code in package RPCB ]

MODULE = RPC  PACKAGE = RPC

[ XS code in package RPC ]</code></pre>

<p>The same package name can be used more than once, allowing for non-contiguous code. This is useful if you have a stronger ordering principle than package names.</p>

<p>Although this keyword is optional and in some cases provides redundant information it should always be used. This keyword will ensure that the XSUBs appear in the desired package.</p>

<h2 id="The-PREFIX-Keyword"><a class="permalink" href="perlxs.html#The-PREFIX-Keyword">#</a><a id="The5"></a>The PREFIX Keyword</h2>

<p>The PREFIX keyword designates prefixes which should be removed from the Perl function names. If the C function is <code>rpcb_gettime()</code> and the PREFIX value is <code>rpcb_</code> then Perl will see this function as <code>gettime()</code>.</p>

<p>This keyword should follow the PACKAGE keyword when used. If PACKAGE is not used then PREFIX should follow the MODULE keyword.</p>

<pre><code class="plaintext">MODULE = RPC  PREFIX = rpc_

MODULE = RPC  PACKAGE = RPCB  PREFIX = rpcb_</code></pre>

<h2 id="The-OUTPUT:-Keyword"><a class="permalink" href="perlxs.html#The-OUTPUT:-Keyword">#</a><a id="The6"></a>The OUTPUT: Keyword</h2>

<p>The OUTPUT: keyword indicates that certain function parameters should be updated (new values made visible to Perl) when the XSUB terminates or that certain values should be returned to the calling Perl function. For simple functions which have no CODE: or PPCODE: section, such as the sin() function above, the RETVAL variable is automatically designated as an output value. For more complex functions the <b>xsubpp</b> compiler will need help to determine which variables are output variables.</p>

<p>This keyword will normally be used to complement the CODE: keyword. The RETVAL variable is not recognized as an output variable when the CODE: keyword is present. The OUTPUT: keyword is used in this situation to tell the compiler that RETVAL really is an output variable.</p>

<p>The OUTPUT: keyword can also be used to indicate that function parameters are output variables. This may be necessary when a parameter has been modified within the function and the programmer would like the update to be seen by Perl.</p>

<pre><code class="plaintext">bool_t
rpcb_gettime(host,timep)
     char *host
     time_t &amp;timep
   OUTPUT:
     timep</code></pre>

<p>The OUTPUT: keyword will also allow an output parameter to be mapped to a matching piece of code rather than to a typemap.</p>

<pre><code>bool_t
rpcb_gettime(host,timep)
     char *host
     time_t &amp;timep
   OUTPUT:
     timep sv_setnv(ST(1), (double)timep);</code></pre>

<p><b>xsubpp</b> emits an automatic <code>SvSETMAGIC()</code> for all parameters in the OUTPUT section of the XSUB, except RETVAL. This is the usually desired behavior, as it takes care of properly invoking &#39;set&#39; magic on output parameters (needed for hash or array element parameters that must be created if they didn&#39;t exist). If for some reason, this behavior is not desired, the OUTPUT section may contain a <code>SETMAGIC: DISABLE</code> line to disable it for the remainder of the parameters in the OUTPUT section. Likewise, <code>SETMAGIC: ENABLE</code> can be used to reenable it for the remainder of the OUTPUT section. See <a href="perlguts.html">perlguts</a> for more details about &#39;set&#39; magic.</p>

<h2 id="The-NO_OUTPUT-Keyword"><a class="permalink" href="perlxs.html#The-NO_OUTPUT-Keyword">#</a><a id="The7"></a>The NO_OUTPUT Keyword</h2>

<p>The NO_OUTPUT can be placed as the first token of the XSUB. This keyword indicates that while the C subroutine we provide an interface to has a non-<code>void</code> return type, the return value of this C subroutine should not be returned from the generated Perl subroutine.</p>

<p>With this keyword present <a href="perlxs.html#The-RETVAL-Variable">&quot;The RETVAL Variable&quot;</a> is created, and in the generated call to the subroutine this variable is assigned to, but the value of this variable is not going to be used in the auto-generated code.</p>

<p>This keyword makes sense only if <code>RETVAL</code> is going to be accessed by the user-supplied code. It is especially useful to make a function interface more Perl-like, especially when the C return value is just an error condition indicator. For example,</p>

<pre><code>  NO_OUTPUT int
  delete_file(char *name)
    POSTCALL:
      if (RETVAL != 0)
	  croak(&quot;Error %d while deleting file &#39;%s&#39;&quot;, RETVAL, name);</code></pre>

<p>Here the generated XS function returns nothing on success, and will die() with a meaningful error message on error.</p>

<h2 id="The-CODE:-Keyword"><a class="permalink" href="perlxs.html#The-CODE:-Keyword">#</a><a id="The8"></a>The CODE: Keyword</h2>

<p>This keyword is used in more complicated XSUBs which require special handling for the C function. The RETVAL variable is still declared, but it will not be returned unless it is specified in the OUTPUT: section.</p>

<p>The following XSUB is for a C function which requires special handling of its parameters. The Perl usage is given first.</p>

<pre><code>$status = rpcb_gettime( &quot;localhost&quot;, $timep );</code></pre>

<p>The XSUB follows.</p>

<pre><code>bool_t
rpcb_gettime(host,timep)
     char *host
     time_t timep
   CODE:
          RETVAL = rpcb_gettime( host, &amp;timep );
   OUTPUT:
     timep
     RETVAL</code></pre>

<h2 id="The-INIT:-Keyword"><a class="permalink" href="perlxs.html#The-INIT:-Keyword">#</a><a id="The9"></a>The INIT: Keyword</h2>

<p>The INIT: keyword allows initialization to be inserted into the XSUB before the compiler generates the call to the C function. Unlike the CODE: keyword above, this keyword does not affect the way the compiler handles RETVAL.</p>

<pre><code>    bool_t
    rpcb_gettime(host,timep)
          char *host
          time_t &amp;timep
	INIT:
	  printf(&quot;# Host is %s\n&quot;, host );
        OUTPUT:
          timep</code></pre>

<p>Another use for the INIT: section is to check for preconditions before making a call to the C function:</p>

<pre><code>    long long
    lldiv(a,b)
	long long a
	long long b
      INIT:
	if (a == 0 &amp;&amp; b == 0)
	    XSRETURN_UNDEF;
	if (b == 0)
	    croak(&quot;lldiv: cannot divide by 0&quot;);</code></pre>

<h2 id="The-NO_INIT-Keyword"><a class="permalink" href="perlxs.html#The-NO_INIT-Keyword">#</a><a id="The10"></a>The NO_INIT Keyword</h2>

<p>The NO_INIT keyword is used to indicate that a function parameter is being used only as an output value. The <b>xsubpp</b> compiler will normally generate code to read the values of all function parameters from the argument stack and assign them to C variables upon entry to the function. NO_INIT will tell the compiler that some parameters will be used for output rather than for input and that they will be handled before the function terminates.</p>

<p>The following example shows a variation of the rpcb_gettime() function. This function uses the timep variable only as an output variable and does not care about its initial contents.</p>

<pre><code class="plaintext">bool_t
rpcb_gettime(host,timep)
     char *host
     time_t &amp;timep = NO_INIT
   OUTPUT:
     timep</code></pre>

<h2 id="The-TYPEMAP:-Keyword"><a class="permalink" href="perlxs.html#The-TYPEMAP:-Keyword">#</a><a id="The11"></a>The TYPEMAP: Keyword</h2>

<p>Starting with Perl 5.16, you can embed typemaps into your XS code instead of or in addition to typemaps in a separate file. Multiple such embedded typemaps will be processed in order of appearance in the XS code and like local typemap files take precedence over the default typemap, the embedded typemaps may overwrite previous definitions of TYPEMAP, INPUT, and OUTPUT stanzas. The syntax for embedded typemaps is</p>

<pre><code class="plaintext">TYPEMAP: &lt;&lt;HERE
... your typemap code here ...
HERE</code></pre>

<p>where the <code>TYPEMAP</code> keyword must appear in the first column of a new line.</p>

<p>Refer to <a href="perlxstypemap.html">perlxstypemap</a> for details on writing typemaps.</p>

<h2 id="Initializing-Function-Parameters"><a class="permalink" href="perlxs.html#Initializing-Function-Parameters">#</a><a id="Initializing"></a>Initializing Function Parameters</h2>

<p>C function parameters are normally initialized with their values from the argument stack (which in turn contains the parameters that were passed to the XSUB from Perl). The typemaps contain the code segments which are used to translate the Perl values to the C parameters. The programmer, however, is allowed to override the typemaps and supply alternate (or additional) initialization code. Initialization code starts with the first <code>=</code>, <code>;</code> or <code>+</code> on a line in the INPUT: section. The only exception happens if this <code>;</code> terminates the line, then this <code>;</code> is quietly ignored.</p>

<p>The following code demonstrates how to supply initialization code for function parameters. The initialization code is eval&#39;ed within double quotes by the compiler before it is added to the output so anything which should be interpreted literally [mainly <code>$</code>, <code>@</code>, or <code>\\</code>] must be protected with backslashes. The variables <code>$var</code>, <code>$arg</code>, and <code>$type</code> can be used as in typemaps.</p>

<pre><code>bool_t
rpcb_gettime(host,timep)
     char *host = (char *)SvPVbyte_nolen($arg);
     time_t &amp;timep = 0;
   OUTPUT:
     timep</code></pre>

<p>This should not be used to supply default values for parameters. One would normally use this when a function parameter must be processed by another library function before it can be used. Default parameters are covered in the next section.</p>

<p>If the initialization begins with <code>=</code>, then it is output in the declaration for the input variable, replacing the initialization supplied by the typemap. If the initialization begins with <code>;</code> or <code>+</code>, then it is performed after all of the input variables have been declared. In the <code>;</code> case the initialization normally supplied by the typemap is not performed. For the <code>+</code> case, the declaration for the variable will include the initialization from the typemap. A global variable, <code>%v</code>, is available for the truly rare case where information from one initialization is needed in another initialization.</p>

<p>Here&#39;s a truly obscure example:</p>

<pre><code>bool_t
rpcb_gettime(host,timep)
     time_t &amp;timep; /* \$v{timep}=@{[$v{timep}=$arg]} */
     char *host + SvOK($v{timep}) ? SvPVbyte_nolen($arg) : NULL;
   OUTPUT:
     timep</code></pre>

<p>The construct <code>\$v{timep}=@{[$v{timep}=$arg]}</code> used in the above example has a two-fold purpose: first, when this line is processed by <b>xsubpp</b>, the Perl snippet <code>$v{timep}=$arg</code> is evaluated. Second, the text of the evaluated snippet is output into the generated C file (inside a C comment)! During the processing of <code>char *host</code> line, <code>$arg</code> will evaluate to <code>ST(0)</code>, and <code>$v{timep}</code> will evaluate to <code>ST(1)</code>.</p>

<h2 id="Default-Parameter-Values"><a class="permalink" href="perlxs.html#Default-Parameter-Values">#</a><a id="Default"></a>Default Parameter Values</h2>

<p>Default values for XSUB arguments can be specified by placing an assignment statement in the parameter list. The default value may be a number, a string or the special string <code>NO_INIT</code>. Defaults should always be used on the right-most parameters only.</p>

<p>To allow the XSUB for rpcb_gettime() to have a default host value the parameters to the XSUB could be rearranged. The XSUB will then call the real rpcb_gettime() function with the parameters in the correct order. This XSUB can be called from Perl with either of the following statements:</p>

<pre><code>$status = rpcb_gettime( $timep, $host );

$status = rpcb_gettime( $timep );</code></pre>

<p>The XSUB will look like the code which follows. A CODE: block is used to call the real rpcb_gettime() function with the parameters in the correct order for that function.</p>

<pre><code>bool_t
rpcb_gettime(timep,host=&quot;localhost&quot;)
     char *host
     time_t timep = NO_INIT
   CODE:
          RETVAL = rpcb_gettime( host, &amp;timep );
   OUTPUT:
     timep
     RETVAL</code></pre>

<h2 id="The-PREINIT:-Keyword"><a class="permalink" href="perlxs.html#The-PREINIT:-Keyword">#</a><a id="The12"></a>The PREINIT: Keyword</h2>

<p>The PREINIT: keyword allows extra variables to be declared immediately before or after the declarations of the parameters from the INPUT: section are emitted.</p>

<p>If a variable is declared inside a CODE: section it will follow any typemap code that is emitted for the input parameters. This may result in the declaration ending up after C code, which is C syntax error. Similar errors may happen with an explicit <code>;</code>-type or <code>+</code>-type initialization of parameters is used (see <a href="perlxs.html#Initializing-Function-Parameters">&quot;Initializing Function Parameters&quot;</a>). Declaring these variables in an INIT: section will not help.</p>

<p>In such cases, to force an additional variable to be declared together with declarations of other variables, place the declaration into a PREINIT: section. The PREINIT: keyword may be used one or more times within an XSUB.</p>

<p>The following examples are equivalent, but if the code is using complex typemaps then the first example is safer.</p>

<pre><code>     bool_t
     rpcb_gettime(timep)
          time_t timep = NO_INIT
	PREINIT:
          char *host = &quot;localhost&quot;;
        CODE:
	  RETVAL = rpcb_gettime( host, &amp;timep );
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>For this particular case an INIT: keyword would generate the same C code as the PREINIT: keyword. Another correct, but error-prone example:</p>

<pre><code>     bool_t
     rpcb_gettime(timep)
          time_t timep = NO_INIT
	CODE:
          char *host = &quot;localhost&quot;;
	  RETVAL = rpcb_gettime( host, &amp;timep );
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>Another way to declare <code>host</code> is to use a C block in the CODE: section:</p>

<pre><code>     bool_t
     rpcb_gettime(timep)
          time_t timep = NO_INIT
	CODE:
	  {
            char *host = &quot;localhost&quot;;
	    RETVAL = rpcb_gettime( host, &amp;timep );
	  }
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>The ability to put additional declarations before the typemap entries are processed is very handy in the cases when typemap conversions manipulate some global state:</p>

<pre><code>    MyObject
    mutate(o)
	PREINIT:
	    MyState st = global_state;
	INPUT:
	    MyObject o;
	CLEANUP:
	    reset_to(global_state, st);</code></pre>

<p>Here we suppose that conversion to <code>MyObject</code> in the INPUT: section and from MyObject when processing RETVAL will modify a global variable <code>global_state</code>. After these conversions are performed, we restore the old value of <code>global_state</code> (to avoid memory leaks, for example).</p>

<p>There is another way to trade clarity for compactness: INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine. Thus the above code for mutate() can be rewritten as</p>

<pre><code>    MyObject
    mutate(o)
	  MyState st = global_state;
	  MyObject o;
	CLEANUP:
	  reset_to(global_state, st);</code></pre>

<p>and the code for rpcb_gettime() can be rewritten as</p>

<pre><code>     bool_t
     rpcb_gettime(timep)
	  time_t timep = NO_INIT
	  char *host = &quot;localhost&quot;;
	C_ARGS:
	  host, &amp;timep
	OUTPUT:
          timep
          RETVAL</code></pre>

<h2 id="The-SCOPE:-Keyword"><a class="permalink" href="perlxs.html#The-SCOPE:-Keyword">#</a><a id="The13"></a>The SCOPE: Keyword</h2>

<p>The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If enabled, the XSUB will invoke ENTER and LEAVE automatically.</p>

<p>To support potentially complex type mappings, if a typemap entry used by an XSUB contains a comment like <code>/*scope*/</code> then scoping will be automatically enabled for that XSUB.</p>

<p>To enable scoping:</p>

<pre><code class="plaintext">SCOPE: ENABLE</code></pre>

<p>To disable scoping:</p>

<pre><code class="plaintext">SCOPE: DISABLE</code></pre>

<h2 id="The-INPUT:-Keyword"><a class="permalink" href="perlxs.html#The-INPUT:-Keyword">#</a><a id="The14"></a>The INPUT: Keyword</h2>

<p>The XSUB&#39;s parameters are usually evaluated immediately after entering the XSUB. The INPUT: keyword can be used to force those parameters to be evaluated a little later. The INPUT: keyword can be used multiple times within an XSUB and can be used to list one or more input variables. This keyword is used with the PREINIT: keyword.</p>

<p>The following example shows how the input parameter <code>timep</code> can be evaluated late, after a PREINIT.</p>

<pre><code>    bool_t
    rpcb_gettime(host,timep)
          char *host
	PREINIT:
	  time_t tt;
	INPUT:
          time_t timep
        CODE:
               RETVAL = rpcb_gettime( host, &amp;tt );
	       timep = tt;
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>The next example shows each input parameter evaluated late.</p>

<pre><code>    bool_t
    rpcb_gettime(host,timep)
	PREINIT:
	  time_t tt;
	INPUT:
          char *host
	PREINIT:
	  char *h;
	INPUT:
          time_t timep
        CODE:
	       h = host;
	       RETVAL = rpcb_gettime( h, &amp;tt );
	       timep = tt;
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>Since INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine, this may be shortened to:</p>

<pre><code>    bool_t
    rpcb_gettime(host,timep)
	  time_t tt;
          char *host;
	  char *h = host;
          time_t timep;
        CODE:
	  RETVAL = rpcb_gettime( h, &amp;tt );
	  timep = tt;
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>(We used our knowledge that input conversion for <code>char *</code> is a &quot;simple&quot; one, thus <code>host</code> is initialized on the declaration line, and our assignment <code>h = host</code> is not performed too early. Otherwise one would need to have the assignment <code>h = host</code> in a CODE: or INIT: section.)</p>

<h2 id="The-IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT-Keywords"><a class="permalink" href="perlxs.html#The-IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT-Keywords">#</a><a id="The15"></a><a id="The-IN-OUTLIST-IN_OUTLIST-OUT-IN_OUT-Keywords"></a>The IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT Keywords</h2>

<p>In the list of parameters for an XSUB, one can precede parameter names by the <code>IN</code>/<code>OUTLIST</code>/<code>IN_OUTLIST</code>/<code>OUT</code>/<code>IN_OUT</code> keywords. <code>IN</code> keyword is the default, the other keywords indicate how the Perl interface should differ from the C interface.</p>

<p>Parameters preceded by <code>OUTLIST</code>/<code>IN_OUTLIST</code>/<code>OUT</code>/<code>IN_OUT</code> keywords are considered to be used by the C subroutine <i>via pointers</i>. <code>OUTLIST</code>/<code>OUT</code> keywords indicate that the C subroutine does not inspect the memory pointed by this parameter, but will write through this pointer to provide additional return values.</p>

<p>Parameters preceded by <code>OUTLIST</code> keyword do not appear in the usage signature of the generated Perl function.</p>

<p>Parameters preceded by <code>IN_OUTLIST</code>/<code>IN_OUT</code>/<code>OUT</code> <i>do</i> appear as parameters to the Perl function. With the exception of <code>OUT</code>-parameters, these parameters are converted to the corresponding C type, then pointers to these data are given as arguments to the C function. It is expected that the C function will write through these pointers.</p>

<p>The return list of the generated Perl function consists of the C return value from the function (unless the XSUB is of <code>void</code> return type or <code>The NO_OUTPUT Keyword</code> was used) followed by all the <code>OUTLIST</code> and <code>IN_OUTLIST</code> parameters (in the order of appearance). On the return from the XSUB the <code>IN_OUT</code>/<code>OUT</code> Perl parameter will be modified to have the values written by the C function.</p>

<p>For example, an XSUB</p>

<pre><code class="plaintext">void
day_month(OUTLIST day, IN unix_time, OUTLIST month)
  int day
  int unix_time
  int month</code></pre>

<p>should be used from Perl as</p>

<pre><code>my ($day, $month) = day_month(time);</code></pre>

<p>The C signature of the corresponding function should be</p>

<pre><code>void day_month(int *day, int unix_time, int *month);</code></pre>

<p>The <code>IN</code>/<code>OUTLIST</code>/<code>IN_OUTLIST</code>/<code>IN_OUT</code>/<code>OUT</code> keywords can be mixed with ANSI-style declarations, as in</p>

<pre><code class="plaintext">void
day_month(OUTLIST int day, int unix_time, OUTLIST int month)</code></pre>

<p>(here the optional <code>IN</code> keyword is omitted).</p>

<p>The <code>IN_OUT</code> parameters are identical with parameters introduced with <a href="perlxs.html#The-%26-Unary-Operator">&quot;The &amp; Unary Operator&quot;</a> and put into the <code>OUTPUT:</code> section (see <a href="perlxs.html#The-OUTPUT%3A-Keyword">&quot;The OUTPUT: Keyword&quot;</a>). The <code>IN_OUTLIST</code> parameters are very similar, the only difference being that the value C function writes through the pointer would not modify the Perl parameter, but is put in the output list.</p>

<p>The <code>OUTLIST</code>/<code>OUT</code> parameter differ from <code>IN_OUTLIST</code>/<code>IN_OUT</code> parameters only by the initial value of the Perl parameter not being read (and not being given to the C function - which gets some garbage instead). For example, the same C function as above can be interfaced with as</p>

<pre><code>void day_month(OUT int day, int unix_time, OUT int month);</code></pre>

<p>or</p>

<pre><code class="plaintext">void
day_month(day, unix_time, month)
    int &amp;day = NO_INIT
    int  unix_time
    int &amp;month = NO_INIT
  OUTPUT:
    day
    month</code></pre>

<p>However, the generated Perl function is called in very C-ish style:</p>

<pre><code>my ($day, $month);
day_month($day, time, $month);</code></pre>

<h2 id="The-length(NAME)-Keyword"><a class="permalink" href="perlxs.html#The-length(NAME)-Keyword">#</a><a id="The16"></a><a id="The-length-NAME-Keyword"></a>The <code>length(NAME)</code> Keyword</h2>

<p>If one of the input arguments to the C function is the length of a string argument <code>NAME</code>, one can substitute the name of the length-argument by <code>length(NAME)</code> in the XSUB declaration. This argument must be omitted when the generated Perl function is called. E.g.,</p>

<pre><code>void
dump_chars(char *s, short l)
{
  short n = 0;
  while (n &lt; l) {
      printf(&quot;s[%d] = \&quot;\\%#03o\&quot;\n&quot;, n, (int)s[n]);
      n++;
  }
}

MODULE = x		PACKAGE = x

void dump_chars(char *s, short length(s))</code></pre>

<p>should be called as <code>dump_chars($string)</code>.</p>

<p>This directive is supported with ANSI-type function declarations only.</p>

<h2 id="Variable-length-Parameter-Lists"><a class="permalink" href="perlxs.html#Variable-length-Parameter-Lists">#</a><a id="Variable"></a>Variable-length Parameter Lists</h2>

<p>XSUBs can have variable-length parameter lists by specifying an ellipsis <code>(...)</code> in the parameter list. This use of the ellipsis is similar to that found in ANSI C. The programmer is able to determine the number of arguments passed to the XSUB by examining the <code>items</code> variable which the <b>xsubpp</b> compiler supplies for all XSUBs. By using this mechanism one can create an XSUB which accepts a list of parameters of unknown length.</p>

<p>The <i>host</i> parameter for the rpcb_gettime() XSUB can be optional so the ellipsis can be used to indicate that the XSUB will take a variable number of parameters. Perl should be able to call this XSUB with either of the following statements.</p>

<pre><code>$status = rpcb_gettime( $timep, $host );

$status = rpcb_gettime( $timep );</code></pre>

<p>The XS code, with ellipsis, follows.</p>

<pre><code>     bool_t
     rpcb_gettime(timep, ...)
          time_t timep = NO_INIT
	PREINIT:
          char *host = &quot;localhost&quot;;
        CODE:
	  if( items &gt; 1 )
	       host = (char *)SvPVbyte_nolen(ST(1));
	  RETVAL = rpcb_gettime( host, &amp;timep );
        OUTPUT:
          timep
          RETVAL</code></pre>

<h2 id="The-C_ARGS:-Keyword"><a class="permalink" href="perlxs.html#The-C_ARGS:-Keyword">#</a><a id="The17"></a>The C_ARGS: Keyword</h2>

<p>The C_ARGS: keyword allows creating of XSUBS which have different calling sequence from Perl than from C, without a need to write CODE: or PPCODE: section. The contents of the C_ARGS: paragraph is put as the argument to the called C function without any change.</p>

<p>For example, suppose that a C function is declared as</p>

<pre><code>symbolic nth_derivative(int n, symbolic function, int flags);</code></pre>

<p>and that the default flags are kept in a global C variable <code>default_flags</code>. Suppose that you want to create an interface which is called as</p>

<pre><code>$second_deriv = $function-&gt;nth_derivative(2);</code></pre>

<p>To do this, declare the XSUB as</p>

<pre><code class="plaintext">    symbolic
    nth_derivative(function, n)
	symbolic	function
	int		n
      C_ARGS:
	n, function, default_flags</code></pre>

<h2 id="The-PPCODE:-Keyword"><a class="permalink" href="perlxs.html#The-PPCODE:-Keyword">#</a><a id="The18"></a>The PPCODE: Keyword</h2>

<p>The PPCODE: keyword is an alternate form of the CODE: keyword and is used to tell the <b>xsubpp</b> compiler that the programmer is supplying the code to control the argument stack for the XSUBs return values. Occasionally one will want an XSUB to return a list of values rather than a single value. In these cases one must use PPCODE: and then explicitly push the list of values on the stack. The PPCODE: and CODE: keywords should not be used together within the same XSUB.</p>

<p>The actual difference between PPCODE: and CODE: sections is in the initialization of <code>SP</code> macro (which stands for the <i>current</i> Perl stack pointer), and in the handling of data on the stack when returning from an XSUB. In CODE: sections SP preserves the value which was on entry to the XSUB: SP is on the function pointer (which follows the last parameter). In PPCODE: sections SP is moved backward to the beginning of the parameter list, which allows <code>PUSH*()</code> macros to place output values in the place Perl expects them to be when the XSUB returns back to Perl.</p>

<p>The generated trailer for a CODE: section ensures that the number of return values Perl will see is either 0 or 1 (depending on the <code>void</code>ness of the return value of the C function, and heuristics mentioned in <a href="perlxs.html#The-RETVAL-Variable">&quot;The RETVAL Variable&quot;</a>). The trailer generated for a PPCODE: section is based on the number of return values and on the number of times <code>SP</code> was updated by <code>[X]PUSH*()</code> macros.</p>

<p>Note that macros <code>ST(i)</code>, <code>XST_m*()</code> and <code>XSRETURN*()</code> work equally well in CODE: sections and PPCODE: sections.</p>

<p>The following XSUB will call the C rpcb_gettime() function and will return its two output values, timep and status, to Perl as a single list.</p>

<pre><code>     void
     rpcb_gettime(host)
          char *host
	PREINIT:
          time_t  timep;
          bool_t  status;
        PPCODE:
          status = rpcb_gettime( host, &amp;timep );
          EXTEND(SP, 2);
          PUSHs(sv_2mortal(newSViv(status)));
          PUSHs(sv_2mortal(newSViv(timep)));</code></pre>

<p>Notice that the programmer must supply the C code necessary to have the real rpcb_gettime() function called and to have the return values properly placed on the argument stack.</p>

<p>The <code>void</code> return type for this function tells the <b>xsubpp</b> compiler that the RETVAL variable is not needed or used and that it should not be created. In most scenarios the void return type should be used with the PPCODE: directive.</p>

<p>The EXTEND() macro is used to make room on the argument stack for 2 return values. The PPCODE: directive causes the <b>xsubpp</b> compiler to create a stack pointer available as <code>SP</code>, and it is this pointer which is being used in the EXTEND() macro. The values are then pushed onto the stack with the PUSHs() macro.</p>

<p>Now the rpcb_gettime() function can be used from Perl with the following statement.</p>

<pre><code>($status, $timep) = rpcb_gettime(&quot;localhost&quot;);</code></pre>

<p>When handling output parameters with a PPCODE section, be sure to handle &#39;set&#39; magic properly. See <a href="perlguts.html">perlguts</a> for details about &#39;set&#39; magic.</p>

<h2 id="Returning-Undef-And-Empty-Lists"><a class="permalink" href="perlxs.html#Returning-Undef-And-Empty-Lists">#</a><a id="Returning1"></a>Returning Undef And Empty Lists</h2>

<p>Occasionally the programmer will want to return simply <code>undef</code> or an empty list if a function fails rather than a separate status value. The rpcb_gettime() function offers just this situation. If the function succeeds we would like to have it return the time and if it fails we would like to have undef returned. In the following Perl code the value of $timep will either be undef or it will be a valid time.</p>

<pre><code>$timep = rpcb_gettime( &quot;localhost&quot; );</code></pre>

<p>The following XSUB uses the <code>SV *</code> return type as a mnemonic only, and uses a CODE: block to indicate to the compiler that the programmer has supplied all the necessary code. The sv_newmortal() call will initialize the return value to undef, making that the default return value.</p>

<pre><code>     SV *
     rpcb_gettime(host)
          char *  host
	PREINIT:
          time_t  timep;
          bool_t x;
        CODE:
          ST(0) = sv_newmortal();
          if( rpcb_gettime( host, &amp;timep ) )
               sv_setnv( ST(0), (double)timep);</code></pre>

<p>The next example demonstrates how one would place an explicit undef in the return value, should the need arise.</p>

<pre><code>     SV *
     rpcb_gettime(host)
          char *  host
	PREINIT:
          time_t  timep;
          bool_t x;
        CODE:
          if( rpcb_gettime( host, &amp;timep ) ){
               ST(0) = sv_newmortal();
               sv_setnv( ST(0), (double)timep);
          }
          else{
               ST(0) = &amp;PL_sv_undef;
          }</code></pre>

<p>To return an empty list one must use a PPCODE: block and then not push return values on the stack.</p>

<pre><code>     void
     rpcb_gettime(host)
          char *host
	PREINIT:
          time_t  timep;
        PPCODE:
          if( rpcb_gettime( host, &amp;timep ) )
               PUSHs(sv_2mortal(newSViv(timep)));
          else{
	      /* Nothing pushed on stack, so an empty
	       * list is implicitly returned. */
          }</code></pre>

<p>Some people may be inclined to include an explicit <code>return</code> in the above XSUB, rather than letting control fall through to the end. In those situations <code>XSRETURN_EMPTY</code> should be used, instead. This will ensure that the XSUB stack is properly adjusted. Consult <a href="perlapi.html">perlapi</a> for other <code>XSRETURN</code> macros.</p>

<p>Since <code>XSRETURN_*</code> macros can be used with CODE blocks as well, one can rewrite this example as:</p>

<pre><code>     int
     rpcb_gettime(host)
          char *host
	PREINIT:
          time_t  timep;
        CODE:
          RETVAL = rpcb_gettime( host, &amp;timep );
	  if (RETVAL == 0)
		XSRETURN_UNDEF;
	OUTPUT:
	  RETVAL</code></pre>

<p>In fact, one can put this check into a POSTCALL: section as well. Together with PREINIT: simplifications, this leads to:</p>

<pre><code>     int
     rpcb_gettime(host)
          char *host
          time_t  timep;
	POSTCALL:
	  if (RETVAL == 0)
		XSRETURN_UNDEF;</code></pre>

<h2 id="The-REQUIRE:-Keyword"><a class="permalink" href="perlxs.html#The-REQUIRE:-Keyword">#</a><a id="The19"></a>The REQUIRE: Keyword</h2>

<p>The REQUIRE: keyword is used to indicate the minimum version of the <b>xsubpp</b> compiler needed to compile the XS module. An XS module which contains the following statement will compile with only <b>xsubpp</b> version 1.922 or greater:</p>

<pre><code class="plaintext">REQUIRE: 1.922</code></pre>

<h2 id="The-CLEANUP:-Keyword"><a class="permalink" href="perlxs.html#The-CLEANUP:-Keyword">#</a><a id="The20"></a>The CLEANUP: Keyword</h2>

<p>This keyword can be used when an XSUB requires special cleanup procedures before it terminates. When the CLEANUP: keyword is used it must follow any CODE:, or OUTPUT: blocks which are present in the XSUB. The code specified for the cleanup block will be added as the last statements in the XSUB.</p>

<h2 id="The-POSTCALL:-Keyword"><a class="permalink" href="perlxs.html#The-POSTCALL:-Keyword">#</a><a id="The21"></a>The POSTCALL: Keyword</h2>

<p>This keyword can be used when an XSUB requires special procedures executed after the C subroutine call is performed. When the POSTCALL: keyword is used it must precede OUTPUT: and CLEANUP: blocks which are present in the XSUB.</p>

<p>See examples in <a href="perlxs.html#The-NO_OUTPUT-Keyword">&quot;The NO_OUTPUT Keyword&quot;</a> and <a href="perlxs.html#Returning-Undef-And-Empty-Lists">&quot;Returning Undef And Empty Lists&quot;</a>.</p>

<p>The POSTCALL: block does not make a lot of sense when the C subroutine call is supplied by user by providing either CODE: or PPCODE: section.</p>

<h2 id="The-BOOT:-Keyword"><a class="permalink" href="perlxs.html#The-BOOT:-Keyword">#</a><a id="The22"></a>The BOOT: Keyword</h2>

<p>The BOOT: keyword is used to add code to the extension&#39;s bootstrap function. The bootstrap function is generated by the <b>xsubpp</b> compiler and normally holds the statements necessary to register any XSUBs with Perl. With the BOOT: keyword the programmer can tell the compiler to add extra statements to the bootstrap function.</p>

<p>This keyword may be used any time after the first MODULE keyword and should appear on a line by itself. The first blank line after the keyword will terminate the code block.</p>

<pre><code>BOOT:
# The following message will be printed when the
# bootstrap function executes.
printf(&quot;Hello from the bootstrap!\n&quot;);</code></pre>

<h2 id="The-VERSIONCHECK:-Keyword"><a class="permalink" href="perlxs.html#The-VERSIONCHECK:-Keyword">#</a><a id="The23"></a>The VERSIONCHECK: Keyword</h2>

<p>The VERSIONCHECK: keyword corresponds to <b>xsubpp</b>&#39;s <code>-versioncheck</code> and <code>-noversioncheck</code> options. This keyword overrides the command line options. Version checking is enabled by default. When version checking is enabled the XS module will attempt to verify that its version matches the version of the PM module.</p>

<p>To enable version checking:</p>

<pre><code class="plaintext">VERSIONCHECK: ENABLE</code></pre>

<p>To disable version checking:</p>

<pre><code class="plaintext">VERSIONCHECK: DISABLE</code></pre>

<p>Note that if the version of the PM module is an NV (a floating point number), it will be stringified with a possible loss of precision (currently chopping to nine decimal places) so that it may not match the version of the XS module anymore. Quoting the $VERSION declaration to make it a string is recommended if long version numbers are used.</p>

<h2 id="The-PROTOTYPES:-Keyword"><a class="permalink" href="perlxs.html#The-PROTOTYPES:-Keyword">#</a><a id="The24"></a>The PROTOTYPES: Keyword</h2>

<p>The PROTOTYPES: keyword corresponds to <b>xsubpp</b>&#39;s <code>-prototypes</code> and <code>-noprototypes</code> options. This keyword overrides the command line options. Prototypes are disabled by default. When prototypes are enabled, XSUBs will be given Perl prototypes. This keyword may be used multiple times in an XS module to enable and disable prototypes for different parts of the module. Note that <b>xsubpp</b> will nag you if you don&#39;t explicitly enable or disable prototypes, with:</p>

<pre><code class="plaintext">Please specify prototyping behavior for Foo.xs (see perlxs manual)</code></pre>

<p>To enable prototypes:</p>

<pre><code class="plaintext">PROTOTYPES: ENABLE</code></pre>

<p>To disable prototypes:</p>

<pre><code class="plaintext">PROTOTYPES: DISABLE</code></pre>

<h2 id="The-PROTOTYPE:-Keyword"><a class="permalink" href="perlxs.html#The-PROTOTYPE:-Keyword">#</a><a id="The25"></a>The PROTOTYPE: Keyword</h2>

<p>This keyword is similar to the PROTOTYPES: keyword above but can be used to force <b>xsubpp</b> to use a specific prototype for the XSUB. This keyword overrides all other prototype options and keywords but affects only the current XSUB. Consult <a href="perlsub.html#Prototypes">&quot;Prototypes&quot; in perlsub</a> for information about Perl prototypes.</p>

<pre><code>    bool_t
    rpcb_gettime(timep, ...)
          time_t timep = NO_INIT
	PROTOTYPE: $;$
	PREINIT:
          char *host = &quot;localhost&quot;;
        CODE:
		  if( items &gt; 1 )
		       host = (char *)SvPVbyte_nolen(ST(1));
		  RETVAL = rpcb_gettime( host, &amp;timep );
        OUTPUT:
          timep
          RETVAL</code></pre>

<p>If the prototypes are enabled, you can disable it locally for a given XSUB as in the following example:</p>

<pre><code class="plaintext">void
rpcb_gettime_noproto()
    PROTOTYPE: DISABLE
...</code></pre>

<h2 id="The-ALIAS:-Keyword"><a class="permalink" href="perlxs.html#The-ALIAS:-Keyword">#</a><a id="The26"></a>The ALIAS: Keyword</h2>

<p>The ALIAS: keyword allows an XSUB to have two or more unique Perl names and to know which of those names was used when it was invoked. The Perl names may be fully-qualified with package names. Each alias is given an index. The compiler will setup a variable called <code>ix</code> which contain the index of the alias which was used. When the XSUB is called with its declared name <code>ix</code> will be 0.</p>

<p>The following example will create aliases <code>FOO::gettime()</code> and <code>BAR::getit()</code> for this function.</p>

<pre><code>    bool_t
    rpcb_gettime(host,timep)
          char *host
          time_t &amp;timep
	ALIAS:
	    FOO::gettime = 1
	    BAR::getit = 2
	INIT:
	  printf(&quot;# ix = %d\n&quot;, ix );
        OUTPUT:
          timep</code></pre>

<h2 id="The-OVERLOAD:-Keyword"><a class="permalink" href="perlxs.html#The-OVERLOAD:-Keyword">#</a><a id="The27"></a>The OVERLOAD: Keyword</h2>

<p>Instead of writing an overloaded interface using pure Perl, you can also use the OVERLOAD keyword to define additional Perl names for your functions (like the ALIAS: keyword above). However, the overloaded functions must be defined in such a way as to accept the number of parameters supplied by perl&#39;s overload system. For most overload methods, it will be three parameters; for the <code>nomethod</code> function it will be four. However, the bitwise operators <code>&amp;</code>, <code>|</code>, <code>^</code>, and <code>~</code> may be called with three <i>or</i> five arguments (see <a href="overload.html">overload</a>).</p>

<p>If any function has the OVERLOAD: keyword, several additional lines will be defined in the c file generated by xsubpp in order to register with the overload magic.</p>

<p>Since blessed objects are actually stored as RV&#39;s, it is useful to use the typemap features to preprocess parameters and extract the actual SV stored within the blessed RV. See the sample for T_PTROBJ_SPECIAL below.</p>

<p>To use the OVERLOAD: keyword, create an XS function which takes three input parameters (or use the C-style &#39;...&#39; definition) like this:</p>

<pre><code class="plaintext">SV *
cmp (lobj, robj, swap)
My_Module_obj    lobj
My_Module_obj    robj
IV               swap
OVERLOAD: cmp &lt;=&gt;
{ /* function defined here */}</code></pre>

<p>In this case, the function will overload both of the three way comparison operators. For all overload operations using non-alpha characters, you must type the parameter without quoting, separating multiple overloads with whitespace. Note that &quot;&quot; (the stringify overload) should be entered as \&quot;\&quot; (i.e. escaped).</p>

<p>Since, as mentioned above, bitwise operators may take extra arguments, you may want to use something like <code>(lobj, robj, swap, ...)</code> (with literal <code>...</code>) as your parameter list.</p>

<h2 id="The-FALLBACK:-Keyword"><a class="permalink" href="perlxs.html#The-FALLBACK:-Keyword">#</a><a id="The28"></a>The FALLBACK: Keyword</h2>

<p>In addition to the OVERLOAD keyword, if you need to control how Perl autogenerates missing overloaded operators, you can set the FALLBACK keyword in the module header section, like this:</p>

<pre><code class="plaintext">MODULE = RPC  PACKAGE = RPC

FALLBACK: TRUE
...</code></pre>

<p>where FALLBACK can take any of the three values TRUE, FALSE, or UNDEF. If you do not set any FALLBACK value when using OVERLOAD, it defaults to UNDEF. FALLBACK is not used except when one or more functions using OVERLOAD have been defined. Please see <a href="overload.html#fallback">&quot;fallback&quot; in overload</a> for more details.</p>

<h2 id="The-INTERFACE:-Keyword"><a class="permalink" href="perlxs.html#The-INTERFACE:-Keyword">#</a><a id="The29"></a>The INTERFACE: Keyword</h2>

<p>This keyword declares the current XSUB as a keeper of the given calling signature. If some text follows this keyword, it is considered as a list of functions which have this signature, and should be attached to the current XSUB.</p>

<p>For example, if you have 4 C functions multiply(), divide(), add(), subtract() all having the signature:</p>

<pre><code>symbolic f(symbolic, symbolic);</code></pre>

<p>you can make them all to use the same XSUB using this:</p>

<pre><code class="plaintext">    symbolic
    interface_s_ss(arg1, arg2)
	symbolic	arg1
	symbolic	arg2
    INTERFACE:
	multiply divide
	add subtract</code></pre>

<p>(This is the complete XSUB code for 4 Perl functions!) Four generated Perl function share names with corresponding C functions.</p>

<p>The advantage of this approach comparing to ALIAS: keyword is that there is no need to code a switch statement, each Perl function (which shares the same XSUB) knows which C function it should call. Additionally, one can attach an extra function remainder() at runtime by using</p>

<pre><code>    CV *mycv = newXSproto(&quot;Symbolic::remainder&quot;,
			  XS_Symbolic_interface_s_ss, __FILE__, &quot;$$&quot;);
    XSINTERFACE_FUNC_SET(mycv, remainder);</code></pre>

<p>say, from another XSUB. (This example supposes that there was no INTERFACE_MACRO: section, otherwise one needs to use something else instead of <code>XSINTERFACE_FUNC_SET</code>, see the next section.)</p>

<h2 id="The-INTERFACE_MACRO:-Keyword"><a class="permalink" href="perlxs.html#The-INTERFACE_MACRO:-Keyword">#</a><a id="The30"></a>The INTERFACE_MACRO: Keyword</h2>

<p>This keyword allows one to define an INTERFACE using a different way to extract a function pointer from an XSUB. The text which follows this keyword should give the name of macros which would extract/set a function pointer. The extractor macro is given return type, <code>CV*</code>, and <code>XSANY.any_dptr</code> for this <code>CV*</code>. The setter macro is given cv, and the function pointer.</p>

<p>The default value is <code>XSINTERFACE_FUNC</code> and <code>XSINTERFACE_FUNC_SET</code>. An INTERFACE keyword with an empty list of functions can be omitted if INTERFACE_MACRO keyword is used.</p>

<p>Suppose that in the previous example functions pointers for multiply(), divide(), add(), subtract() are kept in a global C array <code>fp[]</code> with offsets being <code>multiply_off</code>, <code>divide_off</code>, <code>add_off</code>, <code>subtract_off</code>. Then one can use</p>

<pre><code class="plaintext">    #define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
	((XSINTERFACE_CVT_ANON(ret))fp[CvXSUBANY(cv).any_i32])
    #define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
	CvXSUBANY(cv).any_i32 = CAT2( f, _off )</code></pre>

<p>in C section,</p>

<pre><code class="plaintext">    symbolic
    interface_s_ss(arg1, arg2)
	symbolic	arg1
	symbolic	arg2
      INTERFACE_MACRO:
	XSINTERFACE_FUNC_BYOFFSET
	XSINTERFACE_FUNC_BYOFFSET_set
      INTERFACE:
	multiply divide
	add subtract</code></pre>

<p>in XSUB section.</p>

<h2 id="The-INCLUDE:-Keyword"><a class="permalink" href="perlxs.html#The-INCLUDE:-Keyword">#</a><a id="The31"></a>The INCLUDE: Keyword</h2>

<p>This keyword can be used to pull other files into the XS module. The other files may have XS code. INCLUDE: can also be used to run a command to generate the XS code to be pulled into the module.</p>

<p>The file <i>Rpcb1.xsh</i> contains our <code>rpcb_gettime()</code> function:</p>

<pre><code class="plaintext">bool_t
rpcb_gettime(host,timep)
      char *host
      time_t &amp;timep
    OUTPUT:
      timep</code></pre>

<p>The XS module can use INCLUDE: to pull that file into it.</p>

<pre><code class="plaintext">INCLUDE: Rpcb1.xsh</code></pre>

<p>If the parameters to the INCLUDE: keyword are followed by a pipe (<code>|</code>) then the compiler will interpret the parameters as a command. This feature is mildly deprecated in favour of the <code>INCLUDE_COMMAND:</code> directive, as documented below.</p>

<pre><code class="plaintext">INCLUDE: cat Rpcb1.xsh |</code></pre>

<p>Do not use this to run perl: <code>INCLUDE: perl |</code> will run the perl that happens to be the first in your path and not necessarily the same perl that is used to run <code>xsubpp</code>. See <a href="perlxs.html#The-INCLUDE_COMMAND%3A-Keyword">&quot;The INCLUDE_COMMAND: Keyword&quot;</a>.</p>

<h2 id="The-INCLUDE_COMMAND:-Keyword"><a class="permalink" href="perlxs.html#The-INCLUDE_COMMAND:-Keyword">#</a><a id="The32"></a>The INCLUDE_COMMAND: Keyword</h2>

<p>Runs the supplied command and includes its output into the current XS document. <code>INCLUDE_COMMAND</code> assigns special meaning to the <code>$^X</code> token in that it runs the same perl interpreter that is running <code>xsubpp</code>:</p>

<pre><code class="plaintext">INCLUDE_COMMAND: cat Rpcb1.xsh

INCLUDE_COMMAND: $^X -e ...</code></pre>

<h2 id="The-CASE:-Keyword"><a class="permalink" href="perlxs.html#The-CASE:-Keyword">#</a><a id="The33"></a>The CASE: Keyword</h2>

<p>The CASE: keyword allows an XSUB to have multiple distinct parts with each part acting as a virtual XSUB. CASE: is greedy and if it is used then all other XS keywords must be contained within a CASE:. This means nothing may precede the first CASE: in the XSUB and anything following the last CASE: is included in that case.</p>

<p>A CASE: might switch via a parameter of the XSUB, via the <code>ix</code> ALIAS: variable (see <a href="perlxs.html#The-ALIAS%3A-Keyword">&quot;The ALIAS: Keyword&quot;</a>), or maybe via the <code>items</code> variable (see <a href="perlxs.html#Variable-length-Parameter-Lists">&quot;Variable-length Parameter Lists&quot;</a>). The last CASE: becomes the <b>default</b> case if it is not associated with a conditional. The following example shows CASE switched via <code>ix</code> with a function <code>rpcb_gettime()</code> having an alias <code>x_gettime()</code>. When the function is called as <code>rpcb_gettime()</code> its parameters are the usual <code>(char *host, time_t *timep)</code>, but when the function is called as <code>x_gettime()</code> its parameters are reversed, <code>(time_t *timep, char *host)</code>.</p>

<pre><code>    long
    rpcb_gettime(a,b)
      CASE: ix == 1
	ALIAS:
	  x_gettime = 1
	INPUT:
	  # &#39;a&#39; is timep, &#39;b&#39; is host
          char *b
          time_t a = NO_INIT
        CODE:
               RETVAL = rpcb_gettime( b, &amp;a );
        OUTPUT:
          a
          RETVAL
      CASE:
	  # &#39;a&#39; is host, &#39;b&#39; is timep
          char *a
          time_t &amp;b = NO_INIT
        OUTPUT:
          b
          RETVAL</code></pre>

<p>That function can be called with either of the following statements. Note the different argument lists.</p>

<pre><code>$status = rpcb_gettime( $host, $timep );

$status = x_gettime( $timep, $host );</code></pre>

<h2 id="The-EXPORT_XSUB_SYMBOLS:-Keyword"><a class="permalink" href="perlxs.html#The-EXPORT_XSUB_SYMBOLS:-Keyword">#</a><a id="The34"></a>The EXPORT_XSUB_SYMBOLS: Keyword</h2>

<p>The EXPORT_XSUB_SYMBOLS: keyword is likely something you will never need. In perl versions earlier than 5.16.0, this keyword does nothing. Starting with 5.16, XSUB symbols are no longer exported by default. That is, they are <code>static</code> functions. If you include</p>

<pre><code class="plaintext">EXPORT_XSUB_SYMBOLS: ENABLE</code></pre>

<p>in your XS code, the XSUBs following this line will not be declared <code>static</code>. You can later disable this with</p>

<pre><code class="plaintext">EXPORT_XSUB_SYMBOLS: DISABLE</code></pre>

<p>which, again, is the default that you should probably never change. You cannot use this keyword on versions of perl before 5.16 to make XSUBs <code>static</code>.</p>

<h2 id="The-&amp;-Unary-Operator"><a class="permalink" href="perlxs.html#The-&amp;-Unary-Operator">#</a><a id="The35"></a><a id="The-Unary-Operator"></a>The &amp; Unary Operator</h2>

<p>The <code>&amp;</code> unary operator in the INPUT: section is used to tell <b>xsubpp</b> that it should convert a Perl value to/from C using the C type to the left of <code>&amp;</code>, but provide a pointer to this value when the C function is called.</p>

<p>This is useful to avoid a CODE: block for a C function which takes a parameter by reference. Typically, the parameter should be not a pointer type (an <code>int</code> or <code>long</code> but not an <code>int*</code> or <code>long*</code>).</p>

<p>The following XSUB will generate incorrect C code. The <b>xsubpp</b> compiler will turn this into code which calls <code>rpcb_gettime()</code> with parameters <code>(char *host, time_t timep)</code>, but the real <code>rpcb_gettime()</code> wants the <code>timep</code> parameter to be of type <code>time_t*</code> rather than <code>time_t</code>.</p>

<pre><code class="plaintext">bool_t
rpcb_gettime(host,timep)
      char *host
      time_t timep
    OUTPUT:
      timep</code></pre>

<p>That problem is corrected by using the <code>&amp;</code> operator. The <b>xsubpp</b> compiler will now turn this into code which calls <code>rpcb_gettime()</code> correctly with parameters <code>(char *host, time_t *timep)</code>. It does this by carrying the <code>&amp;</code> through, so the function call looks like <code>rpcb_gettime(host, &amp;timep)</code>.</p>

<pre><code class="plaintext">bool_t
rpcb_gettime(host,timep)
      char *host
      time_t &amp;timep
    OUTPUT:
      timep</code></pre>

<h2 id="Inserting-POD,-Comments-and-C-Preprocessor-Directives"><a class="permalink" href="perlxs.html#Inserting-POD,-Comments-and-C-Preprocessor-Directives">#</a><a id="Inserting"></a><a id="Inserting-POD-Comments-and-C-Preprocessor-Directives"></a>Inserting POD, Comments and C Preprocessor Directives</h2>

<p>C preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:, PPCODE:, POSTCALL:, and CLEANUP: blocks, as well as outside the functions. Comments are allowed anywhere after the MODULE keyword. The compiler will pass the preprocessor directives through untouched and will remove the commented lines. POD documentation is allowed at any point, both in the C and XS language sections. POD must be terminated with a <code>=cut</code> command; <code>xsubpp</code> will exit with an error if it does not. It is very unlikely that human generated C code will be mistaken for POD, as most indenting styles result in whitespace in front of any line starting with <code>=</code>. Machine generated XS files may fall into this trap unless care is taken to ensure that a space breaks the sequence &quot;\n=&quot;.</p>

<p>Comments can be added to XSUBs by placing a <code>#</code> as the first non-whitespace of a line. Care should be taken to avoid making the comment look like a C preprocessor directive, lest it be interpreted as such. The simplest way to prevent this is to put whitespace in front of the <code>#</code>.</p>

<p>If you use preprocessor directives to choose one of two versions of a function, use</p>

<pre><code class="plaintext">#if ... version1
#else /* ... version2  */
#endif</code></pre>

<p>and not</p>

<pre><code class="plaintext">#if ... version1
#endif
#if ... version2
#endif</code></pre>

<p>because otherwise <b>xsubpp</b> will believe that you made a duplicate definition of the function. Also, put a blank line before the #else/#endif so it will not be seen as part of the function body.</p>

<h2 id="Using-XS-With-C++"><a class="permalink" href="perlxs.html#Using-XS-With-C++">#</a><a id="Using"></a><a id="Using-XS-With-C"></a>Using XS With C++</h2>

<p>If an XSUB name contains <code>::</code>, it is considered to be a C++ method. The generated Perl function will assume that its first argument is an object pointer. The object pointer will be stored in a variable called THIS. The object should have been created by C++ with the new() function and should be blessed by Perl with the sv_setref_pv() macro. The blessing of the object by Perl can be handled by a typemap. An example typemap is shown at the end of this section.</p>

<p>If the return type of the XSUB includes <code>static</code>, the method is considered to be a static method. It will call the C++ function using the class::method() syntax. If the method is not static the function will be called using the THIS-&gt;method() syntax.</p>

<p>The next examples will use the following C++ class.</p>

<pre><code>class color {
     public:
     color();
     ~color();
     int blue();
     void set_blue( int );

     private:
     int c_blue;
};</code></pre>

<p>The XSUBs for the blue() and set_blue() methods are defined with the class name but the parameter for the object (THIS, or &quot;self&quot;) is implicit and is not listed.</p>

<pre><code class="plaintext">int
color::blue()

void
color::set_blue( val )
     int val</code></pre>

<p>Both Perl functions will expect an object as the first parameter. In the generated C++ code the object is called <code>THIS</code>, and the method call will be performed on this object. So in the C++ code the blue() and set_blue() methods will be called as this:</p>

<pre><code>RETVAL = THIS-&gt;blue();

THIS-&gt;set_blue( val );</code></pre>

<p>You could also write a single get/set method using an optional argument:</p>

<pre><code>int
color::blue( val = NO_INIT )
    int val
    PROTOTYPE $;$
    CODE:
        if (items &gt; 1)
            THIS-&gt;set_blue( val );
        RETVAL = THIS-&gt;blue();
    OUTPUT:
        RETVAL</code></pre>

<p>If the function&#39;s name is <b>DESTROY</b> then the C++ <code>delete</code> function will be called and <code>THIS</code> will be given as its parameter. The generated C++ code for</p>

<pre><code class="plaintext">void
color::DESTROY()</code></pre>

<p>will look like this:</p>

<pre><code>color *THIS = ...;  // Initialized as in typemap

delete THIS;</code></pre>

<p>If the function&#39;s name is <b>new</b> then the C++ <code>new</code> function will be called to create a dynamic C++ object. The XSUB will expect the class name, which will be kept in a variable called <code>CLASS</code>, to be given as the first argument.</p>

<pre><code class="plaintext">color *
color::new()</code></pre>

<p>The generated C++ code will call <code>new</code>.</p>

<pre><code>RETVAL = new color();</code></pre>

<p>The following is an example of a typemap that could be used for this C++ example.</p>

<pre><code>TYPEMAP
color *  O_OBJECT

OUTPUT
# The Perl object is blessed into &#39;CLASS&#39;, which should be a
# char* having the name of the package for the blessing.
O_OBJECT
    sv_setref_pv( $arg, CLASS, (void*)$var );

INPUT
O_OBJECT
    if( sv_isobject($arg) &amp;&amp; (SvTYPE(SvRV($arg)) == SVt_PVMG) )
        $var = ($type)SvIV((SV*)SvRV( $arg ));
    else{
        warn(\&quot;${Package}::$func_name() -- \&quot;
            \&quot;$var is not a blessed SV reference\&quot;);
        XSRETURN_UNDEF;
    }</code></pre>

<h2 id="Interface-Strategy"><a class="permalink" href="perlxs.html#Interface-Strategy">#</a><a id="Interface"></a>Interface Strategy</h2>

<p>When designing an interface between Perl and a C library a straight translation from C to XS (such as created by <code>h2xs -x</code>) is often sufficient. However, sometimes the interface will look very C-like and occasionally nonintuitive, especially when the C function modifies one of its parameters, or returns failure inband (as in &quot;negative return values mean failure&quot;). In cases where the programmer wishes to create a more Perl-like interface the following strategy may help to identify the more critical parts of the interface.</p>

<p>Identify the C functions with input/output or output parameters. The XSUBs for these functions may be able to return lists to Perl.</p>

<p>Identify the C functions which use some inband info as an indication of failure. They may be candidates to return undef or an empty list in case of failure. If the failure may be detected without a call to the C function, you may want to use an INIT: section to report the failure. For failures detectable after the C function returns one may want to use a POSTCALL: section to process the failure. In more complicated cases use CODE: or PPCODE: sections.</p>

<p>If many functions use the same failure indication based on the return value, you may want to create a special typedef to handle this situation. Put</p>

<pre><code>typedef int negative_is_failure;</code></pre>

<p>near the beginning of XS file, and create an OUTPUT typemap entry for <code>negative_is_failure</code> which converts negative values to <code>undef</code>, or maybe croak()s. After this the return value of type <code>negative_is_failure</code> will create more Perl-like interface.</p>

<p>Identify which values are used by only the C and XSUB functions themselves, say, when a parameter to a function should be a contents of a global variable. If Perl does not need to access the contents of the value then it may not be necessary to provide a translation for that value from C to Perl.</p>

<p>Identify the pointers in the C function parameter lists and return values. Some pointers may be used to implement input/output or output parameters, they can be handled in XS with the <code>&amp;</code> unary operator, and, possibly, using the NO_INIT keyword. Some others will require handling of types like <code>int *</code>, and one needs to decide what a useful Perl translation will do in such a case. When the semantic is clear, it is advisable to put the translation into a typemap file.</p>

<p>Identify the structures used by the C functions. In many cases it may be helpful to use the T_PTROBJ typemap for these structures so they can be manipulated by Perl as blessed objects. (This is handled automatically by <code>h2xs -x</code>.)</p>

<p>If the same C type is used in several different contexts which require different translations, <code>typedef</code> several new types mapped to this C type, and create separate <i>typemap</i> entries for these new types. Use these types in declarations of return type and parameters to XSUBs.</p>

<h2 id="Perl-Objects-And-C-Structures"><a class="permalink" href="perlxs.html#Perl-Objects-And-C-Structures">#</a><a id="Perl"></a>Perl Objects And C Structures</h2>

<p>When dealing with C structures one should select either <b>T_PTROBJ</b> or <b>T_PTRREF</b> for the XS type. Both types are designed to handle pointers to complex objects. The T_PTRREF type will allow the Perl object to be unblessed while the T_PTROBJ type requires that the object be blessed. By using T_PTROBJ one can achieve a form of type-checking because the XSUB will attempt to verify that the Perl object is of the expected type.</p>

<p>The following XS code shows the getnetconfigent() function which is used with ONC+ TIRPC. The getnetconfigent() function will return a pointer to a C structure and has the C prototype shown below. The example will demonstrate how the C pointer will become a Perl reference. Perl will consider this reference to be a pointer to a blessed object and will attempt to call a destructor for the object. A destructor will be provided in the XS source to free the memory used by getnetconfigent(). Destructors in XS can be created by specifying an XSUB function whose name ends with the word <b>DESTROY</b>. XS destructors can be used to free memory which may have been malloc&#39;d by another XSUB.</p>

<pre><code>struct netconfig *getnetconfigent(const char *netid);</code></pre>

<p>A <code>typedef</code> will be created for <code>struct netconfig</code>. The Perl object will be blessed in a class matching the name of the C type, with the tag <code>Ptr</code> appended, and the name should not have embedded spaces if it will be a Perl package name. The destructor will be placed in a class corresponding to the class of the object and the PREFIX keyword will be used to trim the name to the word DESTROY as Perl will expect.</p>

<pre><code>typedef struct netconfig Netconfig;

MODULE = RPC  PACKAGE = RPC

Netconfig *
getnetconfigent(netid)
     char *netid

MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_

void
rpcb_DESTROY(netconf)
     Netconfig *netconf
   CODE:
     printf(&quot;Now in NetconfigPtr::DESTROY\n&quot;);
     free( netconf );</code></pre>

<p>This example requires the following typemap entry. Consult <a href="perlxstypemap.html">perlxstypemap</a> for more information about adding new typemaps for an extension.</p>

<pre><code class="plaintext">TYPEMAP
Netconfig *  T_PTROBJ</code></pre>

<p>This example will be used with the following Perl statements.</p>

<pre><code>use RPC;
$netconf = getnetconfigent(&quot;udp&quot;);</code></pre>

<p>When Perl destroys the object referenced by $netconf it will send the object to the supplied XSUB DESTROY function. Perl cannot determine, and does not care, that this object is a C struct and not a Perl object. In this sense, there is no difference between the object created by the getnetconfigent() XSUB and an object created by a normal Perl subroutine.</p>

<h2 id="Safely-Storing-Static-Data-in-XS"><a class="permalink" href="perlxs.html#Safely-Storing-Static-Data-in-XS">#</a><a id="Safely"></a>Safely Storing Static Data in XS</h2>

<p>Starting with Perl 5.8, a macro framework has been defined to allow static data to be safely stored in XS modules that will be accessed from a multi-threaded Perl.</p>

<p>Although primarily designed for use with multi-threaded Perl, the macros have been designed so that they will work with non-threaded Perl as well.</p>

<p>It is therefore strongly recommended that these macros be used by all XS modules that make use of static data.</p>

<p>The easiest way to get a template set of macros to use is by specifying the <code>-g</code> (<code>--global</code>) option with h2xs (see <a href="h2xs.html">h2xs</a>).</p>

<p>Below is an example module that makes use of the macros.</p>

<pre><code>    #define PERL_NO_GET_CONTEXT
    #include &quot;EXTERN.h&quot;
    #include &quot;perl.h&quot;
    #include &quot;XSUB.h&quot;

    /* Global Data */

    #define MY_CXT_KEY &quot;BlindMice::_guts&quot; XS_VERSION

    typedef struct {
        int count;
        char name[3][100];
    } my_cxt_t;

    START_MY_CXT

    MODULE = BlindMice           PACKAGE = BlindMice

    BOOT:
    {
        MY_CXT_INIT;
        MY_CXT.count = 0;
        strcpy(MY_CXT.name[0], &quot;None&quot;);
        strcpy(MY_CXT.name[1], &quot;None&quot;);
        strcpy(MY_CXT.name[2], &quot;None&quot;);
    }

    int
    newMouse(char * name)
        PREINIT:
          dMY_CXT;
        CODE:
          if (MY_CXT.count &gt;= 3) {
              warn(&quot;Already have 3 blind mice&quot;);
              RETVAL = 0;
          }
          else {
              RETVAL = ++ MY_CXT.count;
              strcpy(MY_CXT.name[MY_CXT.count - 1], name);
          }
        OUTPUT:
          RETVAL

    char *
    get_mouse_name(index)
          int index
        PREINIT:
          dMY_CXT;
        CODE:
          if (index &gt; MY_CXT.count)
            croak(&quot;There are only 3 blind mice.&quot;);
          else
            RETVAL = MY_CXT.name[index - 1];
        OUTPUT:
          RETVAL

    void
    CLONE(...)
	CODE:
	  MY_CXT_CLONE;</code></pre>

<h3 id="MY_CXT-REFERENCE"><a class="permalink" href="perlxs.html#MY_CXT-REFERENCE">#</a><a id="MY_CXT1"></a>MY_CXT REFERENCE</h3>

<dl>

<dt id="MY_CXT_KEY"><a class="permalink" href="perlxs.html#MY_CXT_KEY">#</a>MY_CXT_KEY</dt>
<dd>

<p>This macro is used to define a unique key to refer to the static data for an XS module. The suggested naming scheme, as used by h2xs, is to use a string that consists of the module name, the string &quot;::_guts&quot; and the module version number.</p>

<pre><code class="plaintext">#define MY_CXT_KEY &quot;MyModule::_guts&quot; XS_VERSION</code></pre>

</dd>
<dt id="typedef-my_cxt_t"><a class="permalink" href="perlxs.html#typedef-my_cxt_t">#</a><a id="typedef"></a>typedef my_cxt_t</dt>
<dd>

<p>This struct typedef <i>must</i> always be called <code>my_cxt_t</code>. The other <code>CXT*</code> macros assume the existence of the <code>my_cxt_t</code> typedef name.</p>

<p>Declare a typedef named <code>my_cxt_t</code> that is a structure that contains all the data that needs to be interpreter-local.</p>

<pre><code>typedef struct {
    int some_value;
} my_cxt_t;</code></pre>

</dd>
<dt id="START_MY_CXT"><a class="permalink" href="perlxs.html#START_MY_CXT">#</a>START_MY_CXT</dt>
<dd>

<p>Always place the START_MY_CXT macro directly after the declaration of <code>my_cxt_t</code>.</p>

</dd>
<dt id="MY_CXT_INIT"><a class="permalink" href="perlxs.html#MY_CXT_INIT">#</a>MY_CXT_INIT</dt>
<dd>

<p>The MY_CXT_INIT macro initializes storage for the <code>my_cxt_t</code> struct.</p>

<p>It <i>must</i> be called exactly once, typically in a BOOT: section. If you are maintaining multiple interpreters, it should be called once in each interpreter instance, except for interpreters cloned from existing ones. (But see <a href="perlxs.html#MY_CXT_CLONE">&quot;MY_CXT_CLONE&quot;</a> below.)</p>

</dd>
<dt id="dMY_CXT"><a class="permalink" href="perlxs.html#dMY_CXT">#</a>dMY_CXT</dt>
<dd>

<p>Use the dMY_CXT macro (a declaration) in all the functions that access MY_CXT.</p>

</dd>
<dt id="MY_CXT"><a class="permalink" href="perlxs.html#MY_CXT">#</a>MY_CXT</dt>
<dd>

<p>Use the MY_CXT macro to access members of the <code>my_cxt_t</code> struct. For example, if <code>my_cxt_t</code> is</p>

<pre><code>typedef struct {
    int index;
} my_cxt_t;</code></pre>

<p>then use this to access the <code>index</code> member</p>

<pre><code>dMY_CXT;
MY_CXT.index = 2;</code></pre>

</dd>
<dt id="aMY_CXT/pMY_CXT"><a class="permalink" href="perlxs.html#aMY_CXT/pMY_CXT">#</a><a id="aMY_CXT"></a><a id="aMY_CXT-pMY_CXT"></a>aMY_CXT/pMY_CXT</dt>
<dd>

<p><code>dMY_CXT</code> may be quite expensive to calculate, and to avoid the overhead of invoking it in each function it is possible to pass the declaration onto other functions using the <code>aMY_CXT</code>/<code>pMY_CXT</code> macros, eg</p>

<pre><code>    void sub1() {
	dMY_CXT;
	MY_CXT.index = 1;
	sub2(aMY_CXT);
    }

    void sub2(pMY_CXT) {
	MY_CXT.index = 2;
    }</code></pre>

<p>Analogously to <code>pTHX</code>, there are equivalent forms for when the macro is the first or last in multiple arguments, where an underscore represents a comma, i.e. <code>_aMY_CXT</code>, <code>aMY_CXT_</code>, <code>_pMY_CXT</code> and <code>pMY_CXT_</code>.</p>

</dd>
<dt id="MY_CXT_CLONE"><a class="permalink" href="perlxs.html#MY_CXT_CLONE">#</a>MY_CXT_CLONE</dt>
<dd>

<p>By default, when a new interpreter is created as a copy of an existing one (eg via <code>threads-&gt;create()</code>), both interpreters share the same physical my_cxt_t structure. Calling <code>MY_CXT_CLONE</code> (typically via the package&#39;s <code>CLONE()</code> function), causes a byte-for-byte copy of the structure to be taken, and any future dMY_CXT will cause the copy to be accessed instead.</p>

</dd>
<dt id="MY_CXT_INIT_INTERP(my_perl)"><a class="permalink" href="perlxs.html#MY_CXT_INIT_INTERP(my_perl)">#</a><a id="MY_CXT_INIT_INTERP"></a><a id="MY_CXT_INIT_INTERP-my_perl"></a>MY_CXT_INIT_INTERP(my_perl)</dt>
<dd>

</dd>
<dt id="dMY_CXT_INTERP(my_perl)"><a class="permalink" href="perlxs.html#dMY_CXT_INTERP(my_perl)">#</a><a id="dMY_CXT_INTERP"></a><a id="dMY_CXT_INTERP-my_perl"></a>dMY_CXT_INTERP(my_perl)</dt>
<dd>

<p>These are versions of the macros which take an explicit interpreter as an argument.</p>

</dd>
</dl>

<p>Note that these macros will only work together within the <i>same</i> source file; that is, a dMY_CTX in one source file will access a different structure than a dMY_CTX in another source file.</p>

<h2 id="Thread-aware-system-interfaces"><a class="permalink" href="perlxs.html#Thread-aware-system-interfaces">#</a><a id="Thread"></a>Thread-aware system interfaces</h2>

<p>Starting from Perl 5.8, in C/C++ level Perl knows how to wrap system/library interfaces that have thread-aware versions (e.g. getpwent_r()) into frontend macros (e.g. getpwent()) that correctly handle the multithreaded interaction with the Perl interpreter. This will happen transparently, the only thing you need to do is to instantiate a Perl interpreter.</p>

<p>This wrapping happens always when compiling Perl core source (PERL_CORE is defined) or the Perl core extensions (PERL_EXT is defined). When compiling XS code outside of the Perl core, the wrapping does not take place before Perl 5.28. Starting in that release you can</p>

<pre><code class="plaintext">#define PERL_REENTRANT</code></pre>

<p>in your code to enable the wrapping. It is advisable to do so if you are using such functions, as intermixing the <code>_r</code>-forms (as Perl compiled for multithreaded operation will do) and the <code>_r</code>-less forms is neither well-defined (inconsistent results, data corruption, or even crashes become more likely), nor is it very portable. Unfortunately, not all systems have all the <code>_r</code> forms, but using this <code>#define</code> gives you whatever protection that Perl is aware is available on each system.</p>

<h1 id="EXAMPLES"><a class="permalink" href="perlxs.html#EXAMPLES">#</a>EXAMPLES</h1>

<p>File <code>RPC.xs</code>: Interface to some ONC+ RPC bind library functions.</p>

<pre><code>     #define PERL_NO_GET_CONTEXT
     #include &quot;EXTERN.h&quot;
     #include &quot;perl.h&quot;
     #include &quot;XSUB.h&quot;

     /* Note: On glibc 2.13 and earlier, this needs be &lt;rpc/rpc.h&gt; */
     #include &lt;tirpc/rpc.h&gt;

     typedef struct netconfig Netconfig;

     MODULE = RPC  PACKAGE = RPC

     SV *
     rpcb_gettime(host=&quot;localhost&quot;)
          char *host
	PREINIT:
          time_t  timep;
        CODE:
          ST(0) = sv_newmortal();
          if( rpcb_gettime( host, &amp;timep ) )
               sv_setnv( ST(0), (double)timep );

     Netconfig *
     getnetconfigent(netid=&quot;udp&quot;)
          char *netid

     MODULE = RPC  PACKAGE = NetconfigPtr  PREFIX = rpcb_

     void
     rpcb_DESTROY(netconf)
          Netconfig *netconf
        CODE:
          printf(&quot;NetconfigPtr::DESTROY\n&quot;);
          free( netconf );</code></pre>

<p>File <code>typemap</code>: Custom typemap for RPC.xs. (cf. <a href="perlxstypemap.html">perlxstypemap</a>)</p>

<pre><code class="plaintext">TYPEMAP
Netconfig *  T_PTROBJ</code></pre>

<p>File <code>RPC.pm</code>: Perl module for the RPC extension.</p>

<pre><code>package RPC;

require Exporter;
require DynaLoader;
@ISA = qw(Exporter DynaLoader);
@EXPORT = qw(rpcb_gettime getnetconfigent);

bootstrap RPC;
1;</code></pre>

<p>File <code>rpctest.pl</code>: Perl test program for the RPC extension.</p>

<pre><code>use RPC;

$netconf = getnetconfigent();
$a = rpcb_gettime();
print &quot;time = $a\n&quot;;
print &quot;netconf = $netconf\n&quot;;

$netconf = getnetconfigent(&quot;tcp&quot;);
$a = rpcb_gettime(&quot;poplar&quot;);
print &quot;time = $a\n&quot;;
print &quot;netconf = $netconf\n&quot;;</code></pre>

<p>In Makefile.PL add -ltirpc and -I/usr/include/tirpc.</p>

<h1 id="CAVEATS"><a class="permalink" href="perlxs.html#CAVEATS">#</a>CAVEATS</h1>

<p>XS code has full access to system calls including C library functions. It thus has the capability of interfering with things that the Perl core or other modules have set up, such as signal handlers or file handles. It could mess with the memory, or any number of harmful things. Don&#39;t.</p>

<p>Some modules have an event loop, waiting for user-input. It is highly unlikely that two such modules would work adequately together in a single Perl application.</p>

<p>In general, the perl interpreter views itself as the center of the universe as far as the Perl program goes. XS code is viewed as a help-mate, to accomplish things that perl doesn&#39;t do, or doesn&#39;t do fast enough, but always subservient to perl. The closer XS code adheres to this model, the less likely conflicts will occur.</p>

<p>One area where there has been conflict is in regards to C locales. (See <a href="perllocale.html">perllocale</a>.) perl, with one exception and unless told otherwise, sets up the underlying locale the program is running in to the locale passed into it from the environment. This is an important difference from a generic C language program, where the underlying locale is the &quot;C&quot; locale unless the program changes it. As of v5.20, this underlying locale is completely hidden from pure Perl code outside the lexical scope of <code><span style="white-space: nowrap;">use locale</span></code> except for a couple of function calls in the POSIX module which of necessity use it. But the underlying locale, with that one exception is exposed to XS code, affecting all C library routines whose behavior is locale-dependent. Your XS code better not assume that the underlying locale is &quot;C&quot;. The exception is the <a href="perllocale.html#Category-LC_NUMERIC%3A-Numeric-Formatting"><code>LC_NUMERIC</code></a> locale category, and the reason it is an exception is that experience has shown that it can be problematic for XS code, whereas we have not had reports of problems with the <a href="perllocale.html#WHAT-IS-A-LOCALE">other locale categories</a>. And the reason for this one category being problematic is that the character used as a decimal point can vary. Many European languages use a comma, whereas English, and hence Perl are expecting a dot (U+002E: FULL STOP). Many modules can handle only the radix character being a dot, and so perl attempts to make it so. Up through Perl v5.20, the attempt was merely to set <code>LC_NUMERIC</code> upon startup to the <code>&quot;C&quot;</code> locale. Any <a href="perllocale.html#The-setlocale-function">setlocale()</a> otherwise would change it; this caused some failures. Therefore, starting in v5.22, perl tries to keep <code>LC_NUMERIC</code> always set to <code>&quot;C&quot;</code> for XS code.</p>

<p>To summarize, here&#39;s what to expect and how to handle locales in XS code:</p>

<dl>

<dt id="Non-locale-aware-XS-code"><a class="permalink" href="perlxs.html#Non-locale-aware-XS-code">#</a><a id="Non"></a>Non-locale-aware XS code</dt>
<dd>

<p>Keep in mind that even if you think your code is not locale-aware, it may call a library function that is. Hopefully the man page for such a function will indicate that dependency, but the documentation is imperfect.</p>

<p>The current locale is exposed to XS code except possibly <code>LC_NUMERIC</code> (explained in the next paragraph). There have not been reports of problems with the other categories. Perl initializes things on start-up so that the current locale is the one which is indicated by the user&#39;s environment in effect at that time. See <a href="perllocale.html#ENVIRONMENT">&quot;ENVIRONMENT&quot; in perllocale</a>.</p>

<p>However, up through v5.20, Perl initialized things on start-up so that <code>LC_NUMERIC</code> was set to the &quot;C&quot; locale. But if any code anywhere changed it, it would stay changed. This means that your module can&#39;t count on <code>LC_NUMERIC</code> being something in particular, and you can&#39;t expect floating point numbers (including version strings) to have dots in them. If you don&#39;t allow for a non-dot, your code could break if anyone anywhere changed the locale. For this reason, v5.22 changed the behavior so that Perl tries to keep <code>LC_NUMERIC</code> in the &quot;C&quot; locale except around the operations internally where it should be something else. Misbehaving XS code will always be able to change the locale anyway, but the most common instance of this is checked for and handled.</p>

</dd>
<dt id="Locale-aware-XS-code"><a class="permalink" href="perlxs.html#Locale-aware-XS-code">#</a><a id="Locale"></a>Locale-aware XS code</dt>
<dd>

<p>If the locale from the user&#39;s environment is desired, there should be no need for XS code to set the locale except for <code>LC_NUMERIC</code>, as perl has already set the others up. XS code should avoid changing the locale, as it can adversely affect other, unrelated, code and may not be thread-safe. To minimize problems, the macros <a href="perlapi.html#STORE_LC_NUMERIC_SET_TO_NEEDED">&quot;STORE_LC_NUMERIC_SET_TO_NEEDED&quot; in perlapi</a>, <a href="perlapi.html#STORE_LC_NUMERIC_FORCE_TO_UNDERLYING">&quot;STORE_LC_NUMERIC_FORCE_TO_UNDERLYING&quot; in perlapi</a>, and <a href="perlapi.html#RESTORE_LC_NUMERIC">&quot;RESTORE_LC_NUMERIC&quot; in perlapi</a> should be used to affect any needed change.</p>

<p>But, starting with Perl v5.28, locales are thread-safe on platforms that support this functionality. Windows has this starting with Visual Studio 2005. Many other modern platforms support the thread-safe POSIX 2008 functions. The C <code>#define</code> <code>USE_THREAD_SAFE_LOCALE</code> will be defined iff this build is using these. From Perl-space, the read-only variable <code>${SAFE_LOCALES}</code> is 1 if either the build is not threaded, or if <code>USE_THREAD_SAFE_LOCALE</code> is defined; otherwise it is 0.</p>

<p>The way this works under-the-hood is that every thread has a choice of using a locale specific to it (this is the Windows and POSIX 2008 functionality), or the global locale that is accessible to all threads (this is the functionality that has always been there). The implementations for Windows and POSIX are completely different. On Windows, the runtime can be set up so that the standard <a href="https://perldoc.perl.org/5.35.0/setlocale(3)"><code>setlocale(3)</code></a> function either only knows about the global locale or the locale for this thread. On POSIX, <code>setlocale</code> always deals with the global locale, and other functions have been created to handle per-thread locales. Perl makes this transparent to perl-space code. It continues to use <code>POSIX::setlocale()</code>, and the interpreter translates that into the per-thread functions.</p>

<p>All other locale-sensitive functions automatically use the per-thread locale, if that is turned on, and failing that, the global locale. Thus calls to <code>setlocale</code> are ineffective on POSIX systems for the current thread if that thread is using a per-thread locale. If perl is compiled for single-thread operation, it does not use the per-thread functions, so <code>setlocale</code> does work as expected.</p>

<p>If you have loaded the <a href="POSIX.html"><code>POSIX</code></a> module you can use the methods given in <a href="perlcall.html">perlcall</a> to call <a href="POSIX.html#setlocale"><code>POSIX::setlocale</code></a> to safely change or query the locale (on systems where it is safe to do so), or you can use the new 5.28 function <a href="perlapi.html#Perl_setlocale">&quot;Perl_setlocale&quot; in perlapi</a> instead, which is a drop-in replacement for the system <a href="https://perldoc.perl.org/5.35.0/setlocale(3)"><code>setlocale(3)</code></a>, and handles single-threaded and multi-threaded applications transparently.</p>

<p>There are some locale-related library calls that still aren&#39;t thread-safe because they return data in a buffer global to all threads. In the past, these didn&#39;t matter as locales weren&#39;t thread-safe at all. But now you have to be aware of them in case your module is called in a multi-threaded application. The known ones are</p>

<pre><code class="plaintext">asctime()
ctime()
gcvt() [POSIX.1-2001 only (function removed in POSIX.1-2008)]
getdate()
wcrtomb() if its final argument is NULL
wcsrtombs() if its final argument is NULL
wcstombs()
wctomb()</code></pre>

<p>Some of these shouldn&#39;t really be called in a Perl application, and for others there are thread-safe versions of these already implemented:</p>

<pre><code class="plaintext">asctime_r()
ctime_r()
Perl_langinfo()</code></pre>

<p>The <code>_r</code> forms are automatically used, starting in Perl 5.28, if you compile your code, with</p>

<pre><code class="plaintext">#define PERL_REENTRANT</code></pre>

<p>See also <a href="perlapi.html#Perl_langinfo">&quot;Perl_langinfo&quot; in perlapi</a>. You can use the methods given in <a href="perlcall.html">perlcall</a>, to get the best available locale-safe versions of these</p>

<pre><code class="plaintext">POSIX::localeconv()
POSIX::wcstombs()
POSIX::wctomb()</code></pre>

<p>And note, that some items returned by <code>Localeconv</code> are available through <a href="perlapi.html#Perl_langinfo">&quot;Perl_langinfo&quot; in perlapi</a>.</p>

<p>The others shouldn&#39;t be used in a threaded application.</p>

<p>Some modules may call a non-perl library that is locale-aware. This is fine as long as it doesn&#39;t try to query or change the locale using the system <code>setlocale</code>. But if these do call the system <code>setlocale</code>, those calls may be ineffective. Instead, <a href="perlapi.html#Perl_setlocale"><code>Perl_setlocale</code></a> works in all circumstances. Plain setlocale is ineffective on multi-threaded POSIX 2008 systems. It operates only on the global locale, whereas each thread has its own locale, paying no attention to the global one. Since converting these non-Perl libraries to <code>Perl_setlocale</code> is out of the question, there is a new function in v5.28 <a href="perlapi.html#switch_to_global_locale"><code>switch_to_global_locale</code></a> that will switch the thread it is called from so that any system <code>setlocale</code> calls will have their desired effect. The function <a href="perlapi.html#sync_locale"><code>sync_locale</code></a> must be called before returning to perl.</p>

<p>This thread can change the locale all it wants and it won&#39;t affect any other thread, except any that also have been switched to the global locale. This means that a multi-threaded application can have a single thread using an alien library without a problem; but no more than a single thread can be so-occupied. Bad results likely will happen.</p>

<p>In perls without multi-thread locale support, some alien libraries, such as <code>Gtk</code> change locales. This can cause problems for the Perl core and other modules. For these, before control is returned to perl, starting in v5.20.1, calling the function <a href="perlapi.html#sync_locale">sync_locale()</a> from XS should be sufficient to avoid most of these problems. Prior to this, you need a pure Perl statement that does this:</p>

<pre><code>POSIX::setlocale(LC_ALL, POSIX::setlocale(LC_ALL));</code></pre>

<p>or use the methods given in <a href="perlcall.html">perlcall</a>.</p>

</dd>
</dl>

<h1 id="XS-VERSION"><a class="permalink" href="perlxs.html#XS-VERSION">#</a><a id="XS"></a>XS VERSION</h1>

<p>This document covers features supported by <code>ExtUtils::ParseXS</code> (also known as <code>xsubpp</code>) 3.13_01.</p>

<h1 id="AUTHOR"><a class="permalink" href="perlxs.html#AUTHOR">#</a>AUTHOR</h1>

<p>Originally written by Dean Roehrich &lt;<i>roehrich@cray.com</i>&gt;.</p>

<p>Maintained since 1996 by The Perl Porters &lt;<i>perlbug@perl.org</i>&gt;.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
